Saltar al contenido principal

¿Cómo insertar una imagen en el cuadro de texto?

De forma predeterminada, podemos insertar una imagen o imagen en una hoja de trabajo con la misma rapidez mediante la función Insertar, pero esta función no se aplica a la inserción de una imagen en un cuadro de texto. Con este artículo, puedo ayudarlo a insertar una imagen en un cuadro de texto según lo necesite.

Inserte una imagen o imagen en un cuadro de texto con código VBA


flecha azul burbuja derecha Inserte una imagen o imagen en un cuadro de texto con código VBA

Para insertar una imagen en un cuadro de texto, el siguiente código VBA puede ayudarlo, haga lo siguiente:

1. Inserte un cuadro de texto haciendo clic en recuadro > Cuadro de texto, y luego dibuja un cuadro de texto, mira la captura de pantalla:

doc insertar imagen en el cuadro de texto 1

2. Luego mantenga presionado el ALT + F11 teclas para abrir el Microsoft Visual Basic para aplicaciones ventana.

3. Hacer clic recuadro > Móduloy pegue el siguiente código en el Módulo Ventana.

Código de VBA: inserte una imagen en el cuadro de texto:

Sub ShapePicture()
    Dim xSh As Shape
    Dim xPic As IPictureDisp
    Dim xFileName As String
    xFileName = "C:\Users\DT168\Desktop\pictures\Apple.JPG"
    Set xPic = LoadPicture(xFileName)
    Set xSh = Sheets("Sheet4").Shapes(1)
    xSh.Height = xPic.Height / xPic.Width * xSh.Width
    Set xPic = LoadPicture("")
    Set xPic = Nothing
    xSh.Fill.UserPicture xFileName
End Sub

Note: En el código anterior, Sheet4 es el nombre de la hoja que contiene el cuadro de texto en el que desea insertar la imagen, y C: \ Users \ DT168 \ Desktop \ pictures \ Apple.JPG es la ruta de la imagen que desea insertar, debe cambiarla según sus necesidades.

4. Y luego presione F5 para ejecutar este código, la imagen específica se insertará en el cuadro de texto a la vez, y puede editar el cuadro de texto como lo necesite, vea la captura de pantalla:

doc insertar imagen en el cuadro de texto 2


Artículos relacionados:

¿Cómo establecer un valor predeterminado en un cuadro de texto?

¿Cómo permitir que solo se ingresen números en el cuadro de texto?

¿Cómo aplicar el corrector ortográfico en el cuadro de texto?

¿Cómo cambiar el color del cuadro de texto según el valor en Excel?

Las mejores herramientas de productividad de oficina

🤖 Asistente de IA de Kutools: Revolucionar el análisis de datos basado en: Ejecución inteligente   |  Generar codigo  |  Crear fórmulas personalizadas  |  Analizar datos y generar gráficos  |  Invocar funciones de Kutools...
Características populares: Buscar, resaltar o identificar duplicados   |  Eliminar filas en blanco   |  Combine columnas o celdas sin perder datos   |   Ronda sin fórmula ...
Super búsqueda: Búsqueda virtual de criterios múltiples    Búsqueda V de valores múltiples  |   VLookup en varias hojas   |   Búsqueda difusa ....
Lista desplegable avanzada: Crear rápidamente una lista desplegable   |  Lista desplegable dependiente   |  Lista desplegable de selección múltiple ....
Administrador de columnas: Agregar un número específico de columnas  |  Mover columnas  |  Toggle Estado de visibilidad de columnas ocultas  |  Comparar rangos y columnas ...
Características destacadas: Enfoque de cuadrícula   |  Vista de diseño   |   Gran barra de fórmulas    Administrador de hojas y libros de trabajo   |  Biblioteca de Recursos (Texto automático)   |  Selector de fechas   |  Combinar hojas de trabajo   |  Cifrar/descifrar celdas    Enviar correos electrónicos por lista   |  Súper filtro   |   Filtro especial (filtro negrita/cursiva/tachado...) ...
Los 15 mejores conjuntos de herramientas12 Texto Herramientas (Añadir texto, Quitar caracteres, ...)   |   50+ Tabla Tipos (Diagrama de Gantt, ...)   |   40+ Práctico Fórmulas (Calcular la edad según el cumpleaños, ...)   |   19 Inserción Herramientas (Insertar código QR, Insertar imagen desde la ruta, ...)   |   12 Conversión Herramientas (Números a palabras, Conversión de Moneda, ...)   |   7 Fusionar y dividir Herramientas (Filas combinadas avanzadas, Células partidas, ...)   |   ... y más

Mejore sus habilidades de Excel con Kutools for Excel y experimente la eficiencia como nunca antes. Kutools for Excel ofrece más de 300 funciones avanzadas para aumentar la productividad y ahorrar tiempo.  Haga clic aquí para obtener la función que más necesita...

Descripción


Office Tab lleva la interfaz con pestañas a Office y hace que su trabajo sea mucho más fácil

  • Habilite la edición y lectura con pestañas en Word, Excel, PowerPoint, Publisher, Access, Visio y Project.
  • Abra y cree varios documentos en nuevas pestañas de la misma ventana, en lugar de en nuevas ventanas.
  • ¡Aumenta su productividad en un 50% y reduce cientos de clics del mouse todos los días!
Comments (6)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Yes, I changed both. I did not get any errors when I ran the macro using the F5 key.

I tried to place the macro in different folders of the workbook, worksheet, module,class module but the results were the same: no picture in the text box.


Thanks for writing back. The last name is Hecker, BTW....typo
This comment was minimized by the moderator on the site
Tried this macro on Excel 365. It did not work. Did not receive error message. Macro ran to completion. Picture is not shown in textbox.
This comment was minimized by the moderator on the site
Hello,harvey,
Do you change the sheet name and picture path to your own in the code? Please chek it, thank you!

Note: In the above code, Sheet4 is the sheet name which contains the text box you want to insert picture, and C:\Users\DT168\Desktop\pictures\Apple.JPG is the picture path of the picture you want to insert, you should change them to your need.
This comment was minimized by the moderator on the site
Hi Sky
I have changed the sheet name and the path of the picture. But it still doesn't work.

I got bugs here in "xSh.Fill.UserPicture xFileName"

Many thanks.
Meg
This comment was minimized by the moderator on the site
Hello, Meg,
The code in this article may work well for some simple name picture.
If your picture name is complex, you should apply the below code:
Note: Please change the Text Box 1 to your own name of the textbox.
Sub InsertPicture()
    Dim sPicture As String, pic As Picture
    Dim shp As Shape, shps As ShapeRange  
    sPicture = Application.GetOpenFilename("Pictures (*.gif; *.jpg; *.bmp; *.tif;*.png), *.gif; *.jpg; *.bmp; *.tif; *.png", _
        , "Select Picture to Import") 
    If sPicture = "False" Then Exit Sub   
    Set shp = ActiveSheet.Shapes("Text Box 1")
    Set pic = ActiveSheet.Pictures.Insert(sPicture)
    With pic
        .Name = "My Picture"
        .ShapeRange.LockAspectRatio = msoFalse
        .Height = shp.Height
        .Width = shp.Width
        .Top = shp.Top
        .Left = shp.Left
        .Placement = xlMoveAndSize
    End With
    Set shps = ActiveSheet.Shapes.Range(Array("Text Box 1", "My Picture"))
    shps.Group
    shps.Name = "Pic inside text box"    
    Set pic = Nothing
End Sub


Please have a try, hope it can help you!
If you have any other problem, please comment here.
This comment was minimized by the moderator on the site
It work perfectly. Only change the Text box name as shown:
Set xSh = Sheets("Sheet1").Shapes("TextBox 2")
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations