(Excel VBA)如果单元格值等于“”然后显示/隐藏图像

我正在使用Excel电子表格,当select下拉框的值时,会popup一个图像,如果select了另一个值,它将隐藏当前图像并popup与select相关的图像。 我发现了一些使用坐标的图片和图片定位太耗时的方法; 这不完全是我想要去的路线。在使用StackOverflow之前,我已经做了相当多的研究,到目前为止似乎没有任何工作。 以下是我想要实现的。 我试图保留电子表格中的所有图像,增加了另一个级别的挑战,但我相信有一种方法可以做到这一点,因为excel插入EX时分配图像的数字 图片9

Sub Main() If Range(G11).Value = "anything" Then Picture1 show Picture2 hide End If End Sub 

任何帮助是极大的赞赏。 谢谢

为什么不简单地删除它,而不是隐藏/移动/缩小不需要的图片的大小?

逻辑 :将所有图像保存在临时表中。 当应该显示相关图片时,从临时表中取出并删除前一个。

这是一个例子。

 Sub Sample() Select Case Range("G11").Value Case "Picture 1": ShowPicture ("Picture 1") Case "Picture 2": ShowPicture ("Picture 2") Case "Picture 3": ShowPicture ("Picture 3") Case "Picture 4": ShowPicture ("Picture 4") End Select End Sub Sub ShowPicture(picname As String) '~~> The reason why I am using OERN is because it is much simpler '~~> than looping all shapes and then deleting them. There could be '~~> charts, command buttons and other shapes. I will have to write '~~> extra validation code so that those shapes are not deleted. On Error Resume Next Sheets("Sheet1").Shapes("Picture 1").Delete Sheets("Sheet1").Shapes("Picture 2").Delete Sheets("Sheet1").Shapes("Picture 3").Delete Sheets("Sheet1").Shapes("Picture 4").Delete On Error GoTo 0 Sheets("Temp").Shapes(picname).Copy '<~~ Alternative to the below line. You may re-position the image '<~~ after you paste as per your requirement Sheets("Sheet1").Range("G15").Select Sheets("Sheet1").Paste End Sub 

临时工作表的快照

在这里输入图像描述

这是一个使用对象的Visible属性的解决scheme。 我用这个来显示一个基于字段值的图片。 该领域有一个导致“好”或“坏”的公式。 如果它的价值是“好的”,我想展示一张照片; 对于“坏”,另一张照片应该显示; 他们不应该同时显示。 当用户刷新数据透视表时,该字段需要更新其值,所以我把代码放在数据透视表和图片出现的工作表的那个方法中。

 Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable) 'hide both pictures by loopng through all the shapes on the sheet Dim s As Shape For Each s In ActiveSheet.Shapes 'hide the shape if it is a picture, leave other shapes on the page visible. If s.Type = msoPicture Then s.Visible = msoFalse Next Dim judgement As String 'The field whose value tells what picture to use is a one-cell named range called "judgement" judgement = Range("judgement") 'you need to know which picture is which. If judgement = "Good" Then ActiveSheet.Shapes("Picture 8").Visible = True If judgement = "Bad" Then ActiveSheet.Shapes("Picture 1").Visible = True End Sub 
 Sub hidePicture(myImage) ActiveSheet.Shapes.Range(Array(myImage)).Select Selection.ShapeRange.Height = 0 Selection.ShapeRange.Width = 0 End Sub Sub showPicture(myImage) ActiveSheet.Shapes.Range(Array(myImage)).Select Selection.ShapeRange.Height = 200 Selection.ShapeRange.Width = 300 End Sub 

方便的提示:loggingmacros并查看它生成的代码!

可能更好的是将你的照片“屏幕外”移动,特别是如果它们大小不同。

 Sub Tester() ShowPicture "Picture 3" End Sub Sub ShowPicture(PicName As String) Dim s As Shape For Each s In ActiveSheet.Shapes With s .Top = IIf(.Name = PicName, 100, 100) .Left = IIf(.Name = PicName, 100, 1000) End With Next s End Sub