VBA判断当前路径下格式为png和jpg的图片并插入到另一个工作表的指定单元格
下面是一个示例VBA代码,它可以用来判断当前路径下的png和jpg格式的图片,并将它们插入到另一个工作表的指定单元格中:
Sub InsertImages()
Dim imgPath As String
Dim imgName As String
Dim imgExtension As String
Dim imgType As String
Dim imgCount As Integer
Dim targetSheet As Worksheet
Dim targetCell As Range
Dim i As Integer
' 设置目标工作表和单元格
Set targetSheet = ThisWorkbook.Sheets("Sheet2")
Set targetCell = targetSheet.Range("A1")
' 获取当前路径
imgPath = ThisWorkbook.Path & "\"
' 初始化图片计数器
imgCount = 0
' 循环遍历当前路径下的所有文件
imgName = Dir(imgPath)
Do While imgName <> ""
' 获取文件扩展名
imgExtension = LCase(Right(imgName, Len(imgName) - InStrRev(imgName, ".")))
' 判断文件是否为png或jpg格式
If imgExtension = "png" Or imgExtension = "jpg" Then
' 设置图片类型
If imgExtension = "png" Then
imgType = "PNG"
Else
imgType = "JPEG"
End If
' 插入图片到目标单元格
targetSheet.Pictures.Insert(imgPath & imgName).Select
With Selection
.ShapeRange.LockAspectRatio = msoFalse
.ShapeRange.Width = targetCell.Width
.ShapeRange.Height = targetCell.Height
.ShapeRange.Left = targetCell.Left
.ShapeRange.Top = targetCell.Top
End With
' 移动目标单元格
Set targetCell = targetCell.Offset(1, 0)
' 增加图片计数器
imgCount = imgCount + 1
End If
' 继续遍历下一个文件
imgName = Dir
Loop
' 显示插入的图片数量
MsgBox "共插入了 " & imgCount & " 张图片。"
End Sub
请将上述代码复制到一个VBA模块中,并根据需要修改目标工作表和单元格的名称(在代码中标有注释的部分)。然后,运行InsertImages宏即可。该宏将遍历当前路径下的所有文件,如果文件是png或jpg格式,则将其插入到目标工作表的指定单元格中。在插入完成后,将显示插入的图片数量
原文地址: http://www.cveoy.top/t/topic/hY21 著作权归作者所有。请勿转载和采集!