网站优化

网站优化

Products

当前位置:首页 > 网站优化 >

“如何让Excel批量插入的图片自动适应大小?”

GG网络技术分享 2025-11-12 11:45 7


根据您给的信息,

vba Sub BatchInsertPics Dim picPath As String Dim picName As String Dim picWidth As Single Dim picHeight As Single Dim picRatio As Single Dim cell As Range Dim picFolder As String Dim picFile As String

' 设置图片文件夹路径
picFolder = "D:\图片\" ' 修改为实际的图片文件夹路径
' 用GetOpenFilename函数获取图片文件夹路径
With Application.FileDialog
    .AllowMultiSelect = False
    .Show
    If .SelectedItems.Count> 0 Then
        picFolder = .SelectedItems
    Else
        MsgBox "No folder selected."
        Exit Sub
    End If
End With
' 初始化干活表
Set cell = ThisWorkbook.Sheets.Columns.Cells
' 遍历文件夹中的全部图片文件
picFile = Dir ' Ru果需要其他格式, Neng修改文件
名
Do While picFile <> ""
    ' 插入图片
    With ThisWorkbook.Sheets.Pictures.Insert
        ' 获取图片的实际宽阔度和高大度
        picWidth = .Width
        picHeight = .Height
        ' 计算图片的宽阔高大比
        picRatio = picWidth / picHeight
        ' 调整图片巨大细小以习惯单元格
        If picWidth> cell.Width Then
            .Width = cell.Width
            .Height = cell.Width / picRatio
        ElseIf picHeight> cell.RowHeight Then
            .Height = cell.RowHeight
            .Width = cell.RowHeight * picRatio
        End If
        ' 移动图片到单元格中心
        .Left = cell.Left +  / 2
        .Top = cell.Top +  / 2
        ' 沉命名图片
        .Name = picName
    End With
    ' 移动到下一列
    Set cell = cell.Offset
    ' 获取下一张图片文件
    picFile = Dir
Loop

End Sub

此宏先说说设置图片文件夹的路径,然后用GetOpenFilename函数获取该路径。之后 它遍历文件夹中的全部图片文件,将每张图片插入到干活表的B列中,并根据单元格的巨大细小调整图片的巨大细小,再说说将图片移动到单元格的中心这个。

请在Excel中打开VBA编辑器,然后将此代码粘贴到一个新鲜的模块中。运行此宏时请确保干活表Yi打开,并且您有权限在目标文件夹中写入文件。

标签:

提交需求或反馈

Demand feedback