ChatGPT大师课:VBA带你批量导入图片

如何使用VBA将图片插入到Excel工作表的特定位置。
步骤一:打开VBA编辑器
在Excel中,按Alt + F11键打开VBA编辑器。
步骤二:插入新的模块
在VBA编辑器中,点击菜单中的"插入",然后选择"模块"。
步骤三:复制和粘贴代码
将上述VBA代码复制并粘贴到新模块中。
步骤四:修改代码
1. 将代码中的"Sheet1"替换为你的工作表名。
2. 检查代码中的图片路径"C:\Users\Administrator\Desktop\图片\"是否正确。如果你的图片存放在其他位置,需要将此路径更改为正确的路径。
Sub InsertImages()
Dim ws As Worksheet
Dim rng As Range
Dim img As Picture
Dim imgPath As String
Dim imgName As String
Dim cellWidth As Double, cellHeight As Double
Dim imgWidth As Double, imgHeight As Double
Set ws = ThisWorkbook.Sheets("Sheet1") '你的工作表名
imgPath = "C:\Users\Administrator\Desktop\图片\"
For Each rng In ws.Range("B2:B" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
imgName = rng.Offset(0, -1).Value & ".jfif"
If Dir(imgPath & imgName) <> "" Then
Set img = ws.Pictures.Insert(imgPath & imgName)
With img
cellWidth = rng.Width
cellHeight = rng.Height
imgWidth = cellWidth * 0.9
imgHeight = cellHeight * 0.9
.ShapeRange.LockAspectRatio = msoFalse
.Width = imgWidth
.Height = imgHeight
.Top = rng.Top + (cellHeight - imgHeight) / 2
.Left = rng.Left + (cellWidth - imgWidth) / 2
End With
End If
Next rng
End Sub
步骤五:保存并运行
保存你的Excel工作簿,然后在VBA编辑器中,选择刚刚插入的模块,按F5键或点击菜单栏上的"运行"按钮来执行程序。
步骤六:检查结果
回到Excel工作表,你应该会看到每个人的名字旁边都插入了对应的图片。
这个教程将帮助你使用VBA代码在Excel中插入图片。如果你在使用过程中遇到任何问题,或者你的需求与上述步骤稍有不同,例如你想在其他列插入图片或者更改图片的大小,你都可以按照你的需要对代码进行修改。希望这个教程对你有所帮助!