You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让所有工作表中的图片在单元格内居中对齐?附现有VBA代码

调整工作簿所有图片大小并使其在单元格内居中的VBA代码

以下是修改后的VBA代码,既能批量调整所有图片的尺寸,还能让每张图片在其所在的单元格内水平、垂直居中:

Sub ChangeAllPics()
    Dim s As Shape
    Dim ws As Worksheet
    Dim targetCell As Range
    
    For Each ws In ActiveWorkbook.Sheets
        For Each s In ws.Shapes
            ' 取消宽高比例锁定,设置图片尺寸
            s.LockAspectRatio = msoFalse
            s.Width = 62
            s.Height = 63
            
            ' 获取图片左上角对应的单元格
            Set targetCell = s.TopLeftCell
            
            ' 计算居中位置并赋值,实现单元格内水平+垂直居中
            s.Left = targetCell.Left + (targetCell.Width - s.Width) / 2
            s.Top = targetCell.Top + (targetCell.Height - s.Height) / 2
        Next s
    Next ws
End Sub

关键修改说明

  • 新增targetCell变量,通过Shape.TopLeftCell获取图片左上角所在的单元格对象
  • 利用单元格的边界位置(Left/Top)和尺寸(Width/Height),计算出图片居中时的坐标
  • 将计算得到的坐标赋值给图片的Left和Top属性,完成居中对齐

内容的提问来源于stack exchange,提问作者Arsham Gharbi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 00:47:34