Excel – 删除行时删除图像

我有一个从目录中导入图像的macros,并将它们放置在足够大以适合图像的Excel单元格中

macros的一个片段如下:

'Set the Row Height and Column Width of the thumbnail Range("A" & CStr(currRow)).RowHeight = ThumbnailSizeRef + 2 Columns("A").ColumnWidth = (ThumbnailSizeRef - 5) / 5 'Column Width uses a font width setting, this is the formula to convert to pixels 'Add the thumbnail Set sShape = ActiveSheet.Shapes.AddPicture(Filename:=sFilename, LinktoFile:=msoFalse, SaveWithDocument:=msoTrue, Left:=0, Top:=0, Width:=ThumbnailSizeRef, Height:=ThumbnailSizeRef) 'Set the Left and Top position of the Shape sShape.Left = Range("A" & CStr(currRow)).Left + ((Range("A" & CStr(currRow)).Width - sShape.Width) / 2) sShape.Top = Range("A" & CStr(currRow)).Top + ((Range("A" & CStr(currRow)).Height - sShape.Height) / 2) 

这一切工作正常。 图像根据需要正确显示在单元格中。 我也可以成功地对单元格进行sorting,并且图像可以正确移动。

我遇到的问题是当我删除整个行(右键单击行并删除)…在这种情况下,行Im删除的图像跳下来,并隐藏在下一行的图像后面。

有什么办法,当我删除行图像被删除以及?

您可以将图片属性更改为“使用单元格移动和resize”。 因此,当你删除你的行,你的图像也将被删除。 在Excel 2007中testing。

另一个解决scheme是添加评论,并在背景中填写图片(详情请参阅: http : //www.excelforum.com/excel-general/569566-embed-image-in-cell.html )

可能有更好的方法,但我可以想到2个解决方法。

  1. 将形状导入到单元格时,请特别使用命名约定来命名形状以标识行/列(例如.Name =“ImageX-RowY-ColumnZ”)。 然后使用工作表更改事件,并通过此链接捕获已删除的行来遍历形状,并根据删除的内容删除所需的形状。

  2. 或者,填写一个评论框与您的形象,当行被删除的评论和形象也消失

例如

  Sub test() ThumbnailSizeRef = 100 currRow = 5 sFilename = "C:\Users\....\Desktop\Untitled.png" Range("A" & CStr(currRow)).RowHeight = ThumbnailSizeRef + 2 Columns("A").ColumnWidth = (ThumbnailSizeRef - 5) / 5 With Sheet1 With .Range("A" & currRow) .ClearComments .AddComment With .Comment .Visible = True .Text Text:="" .Shape.Left = Sheet1.Range("A" & currRow).Left .Shape.Top = Sheet1.Range("A" & currRow).Top .Shape.Width = Sheet1.Range("A" & currRow).Offset(0, 1).Left - Sheet1.Range("A" & currRow).Left .Shape.Height = Sheet1.Range("A" & currRow).Offset(1, 0).Top - Sheet1.Range("A" & currRow).Top .Shape.Fill.UserPicture sFilename .Shape.Line.ForeColor.RGB = RGB(255, 255, 255) 'hides connector arrow End With End With End With End Sub 

这并不完美,但它可能会满足您的需求,或者至less让您朝着正确的方向前进。

把这段代码放在工作表模块中。 当一个事件改变整行时,它将删除它find的左上angular的单元格在该行中的第一个形状。 如果您要删除一行,这将起作用,但是如果您剪切了一行,也会触发它,这是不希望的。 如果你不打算切割和粘贴行,这不是一个问题。

 Private Sub Worksheet_Change(ByVal Target As Range) Dim pic As Shape If Union(Target, Target.EntireRow).Address = Target.Address Then For Each pic In ActiveSheet.Shapes If pic.TopLeftCell.Row = Target.Row Then pic.Delete Exit For End If Next pic End If End Sub