下面是一个可以自动调整指定列的表格图片大小的 VBA 代码示例:

Sub AutoResizePictures()
    Dim ws As Worksheet
    Dim rng As Range
    Dim shp As Shape
    Dim colNum As Long
    Dim colWidth As Double
    Dim shpWidth As Double
    Dim shpHeight As Double
    
    '设置要调整大小的列号和列宽度
    colNum = 2
    colWidth = 100
    
    Set ws = ActiveSheet
    Set rng = ws.Columns(colNum)
    
    '将列宽度设置为指定宽度
    rng.ColumnWidth = colWidth
    
    '遍历列中的所有形状,并自动调整大小
    For Each shp In ws.Shapes
        If Not Intersect(shp.TopLeftCell, rng) Is Nothing Then
            shpWidth = shp.Width
            shpHeight = shp.Height
            shp.LockAspectRatio = msoFalse
            shp.Width = colWidth - 5
            shp.Height = (shpHeight / shpWidth) * (colWidth - 5)
            shp.LockAspectRatio = msoTrue
        End If
    Next shp
End Sub

此代码适用于以下情况:

  • 指定一个要调整大小的列号和宽度
  • 将该列的宽度设置为指定宽度
  • 遍历该列中的所有形状
  • 对于每个形状,将其宽度调整为列宽度减去一些余量(这里设置为 5,可以根据需要进行调整),然后根据原始宽高比计算出相应的高度
  • 最后将形状的锁定纵横比设置为真,以确保其保持正确的宽高比

请注意,此代码假定您只有单个表格中的图片,如果您有多个表格中的图片,则需要对代码进行修改以适应多个表格和不同的列。

Excel VBA 自动调整指定列表格图片大小

原文地址: https://www.cveoy.top/t/topic/mAJ8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录