2012-02-08 19 views
5

Estoy trabajando en una hoja de cálculo de Excel que cuando se selecciona un valor de cuadro desplegable aparecerá una imagen, y si se selecciona otro valor se ocultará la actual imagen y pop-up de la imagen relacionada con la selección. He encontrado algunos métodos que consumen demasiado tiempo usando solo la hoja y el posicionamiento de la imagen usando coordenadas; esa no es exactamente la ruta a la que me gustaría ir. He investigado un poco antes de usar StackOverflow, y hasta el momento nada parecía funcionar. Debajo está lo que estoy intentando alcanzar. Estoy tratando de mantener todas las imágenes dentro de la hoja de cálculo, lo que agrega otro nivel de desafío, pero creo que hay una manera de hacerlo porque Excel asigna un número a la imagen cuando se inserta EX. Imagen 9.(Excel VBA) Si Cell Value es igual a "" Entonces Mostrar/Ocultar imágenes

Sub Main() 
    If Range(G11).Value = "anything" Then 

    Picture1 show 

    Picture2 hide 

    End If 
End Sub 

Cualquier ayuda es muy apreciada. Gracias

Respuesta

5

En lugar de ocultar/mover/reducir el tamaño de la foto no deseada, ¿por qué no simplemente eliminarla?

Logic: Guarde todas sus imágenes en una hoja temporal. Cuando se supone que debe mostrarse una imagen relevante, obténgalo de la hoja temporal y elimine el anterior.

Aquí hay un ejemplo.

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 

Snapshot de hoja temp

enter image description here

0
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 

Consejo práctico: ¡graba la macro y mira el código que genera!

+0

hice hacer eso, pero nunca habría pensado que acaba de reducirla a la nada gracias por la solución va a tratar ahora –

+0

No hubo suerte en la que sólo se permite una sola imagen no se puede hacer de varias imágenes. Tenía la esperanza de que el uso de un valor de celda controlaría qué imagen se muestra –

0

Sería mejor simplemente mover sus imágenes "fuera de pantalla", especialmente si son de diferentes tamaños.

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 
2

Aquí es una solución utilizando la propiedad Visible del objeto. Lo usé para mostrar una imagen basada en un valor en un campo. El campo tenía una fórmula que daba como resultado "bueno" o "malo". Si su valor era "bueno", quería mostrar una imagen; para "malo", debería mostrarse otra imagen; y nunca deberían mostrarse al mismo tiempo. El campo necesitaba actualizar su valor cada vez que un usuario actualizaba una tabla dinámica, así que puse el código en ese método de la hoja de trabajo donde aparecerían la tabla dinámica y la imagen.

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 
+0

Bastante útil, gracias. – JCO9