批量将文件夹内的图片插入到与图片名称相匹配的Excel单元格中,技巧收藏!
Excel情报局
Excel职场联盟




前言|职场实例

方案|解决方法

Sub InserPictureByName()Dim xFDObject As FileDialogDim xStrPath, xStrPicPath As StringDim xRgName, xRgInser, xRg, xRgI As RangeDim xFNum As IntegerSet xFDObject = Application.FileDialog(msoFileDialogFolderPicker)With xFDObject .Title = "Please select the folder:" .InitialFileName = Application.ActiveWorkbook.Path .Show .AllowMultiSelect = FalseEnd WithOn Error Resume NextxStrPath = ""xStrPath = xFDObject.SelectedItems.Item(1)If xStrPath = "" ThenExit SubEnd IfSet xRgName = Application.InputBox("Please select the cells contain the image name:", "Kutools for Excel", , , , , , 8)If xRgName Is Nothing Then MsgBox "No cells are select, exit operation! ", vbInformation, "Kutools for Excel" Exit SubEnd IfSet xRgInser = Application.InputBox("Please select the cells to output the images", "Kutools for Excel", , , , , , 8)If xRgInser Is Nothing Then MsgBox " No cells are select, exit operation.! ", vbInformation, "Kutools for Excel" Exit SubEnd IfFor xFNum = 1 To xRgName.Count Set xRg = xRgName.Item(xFNum) Set xRgI = xRgInser.Item(xFNum) xStrPicPath = xStrPath & "\" & xRg.Text & ".jpg" If Not Dir(xStrPicPath, vbDirectory) = vbNullString Then With xRgI.Parent.Pictures.Insert(xStrPicPath) .Left = xRgI.Left .Top = xRgI.Top .ShapeRange.LockAspectRatio = msoFalse .ShapeRange.Height = 60 .ShapeRange.Width = 60 End With End IfNextEnd Sub
在“选择工作表中图片名称的单元格区域”的选择框中,我们在工作表中框选单元格区域:A2:A4,然后点击“确定”按钮,又继续弹出一个“选择插入图片存放在表格中位置”的对话框,如下图所示:


注意|代码灵活修改的地方
.ShapeRange.Height = 60
.ShapeRange.Width = 60





赞 (0)
