excel - 从单元格中删除所有图像,除了 vba 中的最后一个

标签 excel vba

我在单元格中有相同的图像,所以我想删除除最后一个之外的所有图像(只保留一个)。
我有下面的代码,但它只适用于一个单元格。我看到删除代码有问题。

Sub CellImageCheck()  '' Delete multiple images in cells
    Dim checkRange As Range
    Dim x As Shape
    Dim flag As Boolean
    'On Error Resume Next

Dim WorkRng As Range
Set WorkRng = Range("E1:E372")

        For Each x In ActiveSheet.Shapes
            m = Range(x.TopLeftCell.Address).Row
            Cells(m, 7).Value = Cells(m, 7).Value + 1 '' write image count from cell in respetice row in E column
        Next
        
        ''' Delete all images in cell except last
        For Each x In ActiveSheet.Shapes
        m = Range(x.TopLeftCell.Address).Row
        
            For Each Rng In WorkRng
                If Cells(m, 7).Value > 1 Then
                    Cells(m, 7).Value = Cells(m, 7).Value - 1
                    x.Delete
                End If
            Next
        Next
End Sub

最佳答案

您可以使用字典来跟踪哪些单元格已与形状关联,然后删除也与同一单元格关联的任何“额外”形状。

Sub CellImageCheck()  
    
    Dim i As Long, addr, dict As Object
    
    Set dict = CreateObject("scripting.dictionary")
    
    For i = ActiveSheet.Shapes.Count To 1 Step -1
        With ActiveSheet.Shapes(i)
            addr = .TopLeftCell.Address(0, 0)
            If Not dict.exists(addr) Then
                dict.Add addr, True  'first shape over this cell
            Else
                .Delete              'already have a shape for this cell
            End If
        End With
    Next i
End Sub

关于excel - 从单元格中删除所有图像,除了 vba 中的最后一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68457872/

相关文章:

vba - 带有 float 的 Mod 给出错误的结果

vba - 将 div0 错误更改为一个值(获取错误 13)vba excel

excel - SAP GUI 脚本打开一个 Excel 窗口,我无法停止它

c# - 将大量记录保存到 XLS 的最佳方法

excel - 数据透视表无法找到当年 1 月与上年 12 月之间的差异。 Excel 2010

excel - VBA,修剪路径的一部分

ms-access - MS Access 属性

vba - 如果单元格包含一组单词中的一个单词,则检查 VBA 子

excel - 如何正确粘贴excel公式

excel - 最大化打开 Excel 电子表格