ChatGPT大師課:VBA帶你批量導(dǎo)入圖片

如何使用VBA將圖片插入到Excel工作表的特定位置。
步驟一:打開(kāi)VBA編輯器
在Excel中,按Alt + F11鍵打開(kāi)VBA編輯器。
步驟二:插入新的模塊
在VBA編輯器中,點(diǎn)擊菜單中的"插入",然后選擇"模塊"。
步驟三:復(fù)制和粘貼代碼
將上述VBA代碼復(fù)制并粘貼到新模塊中。
步驟四:修改代碼
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
步驟五:保存并運(yùn)行
保存你的Excel工作簿,然后在VBA編輯器中,選擇剛剛插入的模塊,按F5鍵或點(diǎn)擊菜單欄上的"運(yùn)行"按鈕來(lái)執(zhí)行程序。
步驟六:檢查結(jié)果
回到Excel工作表,你應(yīng)該會(huì)看到每個(gè)人的名字旁邊都插入了對(duì)應(yīng)的圖片。
這個(gè)教程將幫助你使用VBA代碼在Excel中插入圖片。如果你在使用過(guò)程中遇到任何問(wèn)題,或者你的需求與上述步驟稍有不同,例如你想在其他列插入圖片或者更改圖片的大小,你都可以按照你的需要對(duì)代碼進(jìn)行修改。希望這個(gè)教程對(duì)你有所幫助!