【发布时间】:2013-08-12 14:02:58
【问题描述】:
我有一本工作簿,其中有几行有图片。当我删除整行时,图片会留在它后面。
我需要做的是找到可以让我删除所选行和图片的 vba 代码。
我该怎么做?
【问题讨论】:
标签: excel row-removal vba
我有一本工作簿,其中有几行有图片。当我删除整行时,图片会留在它后面。
我需要做的是找到可以让我删除所选行和图片的 vba 代码。
我该怎么做?
【问题讨论】:
标签: excel row-removal vba
以下是帮助您入门的内容:
Option Explicit
Public Sub deletePics()
Dim pic As Shape
For Each pic In ActiveSheet.Shapes
If (pic.Type = msoPicture) Then
Debug.Print pic.TopLeftCell.Address
End If
Next pic
End Sub
您可以遍历所有图片,并收集它们的地址(或仅行)并将其存储在一个数组中。当您遍历删除代码时,您可以将行和数组传递给一个函数,该函数将检查该行中是否有图片,如果有,将其删除(使用pic.Delete)。
编辑:
由于这比平常更复杂,而且您是 VBA 新手,这里有一个更具体的示例:
Option Explicit
Public Function deleteCells()
Dim lastRow As Long
Dim ws As Worksheet
Dim rowHasPic() As Shape
Set ws = ActiveSheet
rowHasPic = getPicData()
' get last row
lastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
Dim i As Long
' loop through cells from bottom to top, deleting rows that contain "Delete" in column a
' and delete the pic as well
For i = lastRow To 1 Step -1
If (ws.Cells(i, 1).Value = "delete") Then
' delete pic first, if available
If (Not rowHasPic(i) Is Nothing) Then rowHasPic(i).Delete
ws.Cells(i, 1).EntireRow.Delete
End If
Next i
End Function
Public Function getPicData() As Shape()
Dim ws As Worksheet
Dim pic As Shape
Dim a() As Shape
Dim lastRow As Long
Set ws = ActiveSheet
lastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
' set the boundaries as if they are rows in a worksheet
' this is so we can easily check if a row has a pic later in the code
ReDim a(1 To lastRow)
' loop through the shapes, only grab pictures and set their row in an array
For Each pic In ActiveSheet.Shapes
If (pic.Type = msoPicture) Then
' set the particular "row" of the array to true to know if you
' have an image in this row
Set a(pic.TopLeftCell.Row) = pic
End If
Next pic
getPicData = a
End Function
总而言之,我创建了一个 Shapes 数组,使数组索引与工作表上的行数相匹配。当我遍历工作表中的所有形状时,我会检查它是否是图片,如果是,则将其设置到该特定行的数组中。
然后,我从下到上遍历工作表,并检查 A 列中的“删除”以确定是否应该删除它。
如果我发现 A 列的文本中有“删除”,那么我会检查数组中的图像,如果存在,则将其删除。然后我删除整行。
注意
如果您在同一行中有多张图片,这将不适合您。您必须以不同的方式对其进行编码。
【讨论】: