删除带图片的行?

时间:2013-08-12 14:02:58

标签: excel excel-vba row-removal vba

我有一个工作簿,并且有几行包含图片。当我删除整行时,图片会留在它后面。

我需要做的是找到可以删除所选行和图片的vba代码。

我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

这是让你入门的东西:

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,如果有,则删除它(使用pic.Delete)。 / p>

编辑:

由于这比平时更复杂,而且你是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数组,以便数组索引匹配工作表上的行数。当我遍历工作表中的所有形状时,我会检查它是否为pic,如果是,则将其设置为该特定行的数组。

然后,我从下到上遍历工作表,并检查A列中的“删除”,以确定是否应删除它。

如果我发现在A列中文本中有“删除”,那么我检查数组中的图像,如果它在那里,则删除它。然后我删除整行。

注意

如果您在同一行中有多个图片,这将不适合您。你必须以不同的方式编码。