VBA Code: Resize and Center Shapes in Excel
This VBA code locks the aspect ratio of all shapes on the active sheet, and then resizes and centers specific shapes based on their position in the worksheet.
The shapes located in cells L9:L16 are resized to 87.874015748 units in height and width, and then centered within their respective cells.
Note: This code uses hard-coded cell addresses to determine which shapes to resize and center. If the layout of the worksheet changes, the code will need to be modified accordingly.
Sub nnn()
Dim sh As Shape
On Error Resume Next
For Each sh In ActiveSheet.Shapes
sh.LockAspectRatio = msoFalse
If sh.TopLeftCell.Address = '$L$9' Then
sh.Height = 87.874015748
sh.Width = 87.874015748
sh.Left = (sh.TopLeftCell.Width - sh.Width) / 2 + sh.TopLeftCell.Left '定义图片位置于所在单元格中间位置
sh.Top = (sh.TopLeftCell.Height - sh.Height) / 2 + sh.TopLeftCell.Top '定义图片位置于所在单元格中间位置
ElseIf sh.TopLeftCell.Address = '$L$10' Then
sh.Height = 87.874015748
sh.Width = 87.874015748
sh.Left = (sh.TopLeftCell.Width - sh.Width) / 2 + sh.TopLeftCell.Left '定义图片位置于所在单元格中间位置
sh.Top = (sh.TopLeftCell.Height - sh.Height) / 2 + sh.TopLeftCell.Top '定义图片位置于所在单元格中间位置
ElseIf sh.TopLeftCell.Address = '$L$11' Then
sh.Height = 87.874015748
sh.Width = 87.874015748
sh.Left = (sh.TopLeftCell.Width - sh.Width) / 2 + sh.TopLeftCell.Left '定义图片位置于所在单元格中间位置
sh.Top = (sh.TopLeftCell.Height - sh.Height) / 2 + sh.TopLeftCell.Top '定义图片位置于所在单元格中间位置
ElseIf sh.TopLeftCell.Address = '$L$12' Then
sh.Height = 87.874015748
sh.Width = 87.874015748
sh.Left = (sh.TopLeftCell.Width - sh.Width) / 2 + sh.TopLeftCell.Left '定义图片位置于所在单元格中间位置
sh.Top = (sh.TopLeftCell.Height - sh.Height) / 2 + sh.TopLeftCell.Top '定义图片位置于所在单元格中间位置
ElseIf sh.TopLeftCell.Address = '$L$13' Then
sh.Height = 87.874015748
sh.Width = 87.874015748
sh.Left = (sh.TopLeftCell.Width - sh.Width) / 2 + sh.TopLeftCell.Left '定义图片位置于所在单元格中间位置
sh.Top = (sh.TopLeftCell.Height - sh.Height) / 2 + sh.TopLeftCell.Top '定义图片位置于所在单元格中间位置
ElseIf sh.TopLeftCell.Address = '$L$14' Then
sh.Height = 87.874015748
sh.Width = 87.874015748
sh.Left = (sh.TopLeftCell.Width - sh.Width) / 2 + sh.TopLeftCell.Left '定义图片位置于所在单元格中间位置
sh.Top = (sh.TopLeftCell.Height - sh.Height) / 2 + sh.TopLeftCell.Top '定义图片位置于所在单元格中间位置
ElseIf sh.TopLeftCell.Address = '$L$15' Then
sh.Height = 87.874015748
sh.Width = 87.874015748
sh.Left = (sh.TopLeftCell.Width - sh.Width) / 2 + sh.TopLeftCell.Left '定义图片位置于所在单元格中间位置
sh.Top = (sh.TopLeftCell.Height - sh.Height) / 2 + sh.TopLeftCell.Top '定义图片位置于所在单元格中间位置
ElseIf sh.TopLeftCell.Address = '$L$16' Then
sh.Height = 87.874015748
sh.Width = 87.874015748
sh.Left = (sh.TopLeftCell.Width - sh.Width) / 2 + sh.TopLeftCell.Left '定义图片位置于所在单元格中间位置
sh.Top = (sh.TopLeftCell.Height - sh.Height) / 2 + sh.TopLeftCell.Top '定义图片位置于所在单元格中间位置
End If
Next
End Sub
原文地址: http://www.cveoy.top/t/topic/mAww 著作权归作者所有。请勿转载和采集!