循环通过形状来获得Dimensions

时间:2017-03-06 04:57:49

标签: vba excel-vba excel

我目前有一大堆工作簿,每个工作簿都包含一个包含数百种形状的工作表,我需要一个代码来选择最宽的形状并获得其宽度值。 谢谢

txtCell.textFieldData

2 个答案:

答案 0 :(得分:1)

您可以使用Function返回最宽的形状并设置其宽度

Function GetWidestShape(widestShpWidth As Long) As Shape
    Dim shp As Shape

    For Each shp In ActiveSheet.Shapes
      If shp.Width > widestShpWidth Then
           widestShpWidth = shp.Width
           Set GetWidestShape = shp
      End If
    Next
End Function

您可以在主代码中利用如下:

Sub Main()
    Dim widestShp As Shape
    Dim widestShpWidth As Long

    Set widestShp = GetWidestShape(widestShpWidth) '<--| get the widest shape along with ist width 
    With widestShp
        ' ...
        ' your code to act on referenced shape
        '...
    End With
End Sub

当然方法也是可能的:

Function GetWidestShapeWidth(widestShp As Shape) As Long
    Dim shp As Shape
    Dim widestShpWidth As Long

    For Each shp In ActiveSheet.Shapes
      If shp.Width > widestShpWidth Then
           widestShpWidth = shp.Width
           Set widestShp = shp
      End If
    Next
End Function


Sub Main()
    Dim widestShp As Shape
    Dim widestShpWidth As Long

    widestShpWidth = GetWidestShapeWidth(widestShp) '<--| get the width of the widest shape along with the widest shape        
    With widestShp
        ' ...
        ' your code to act on referenced shape
        '...
    End With
End Sub

答案 1 :(得分:0)

猜测它会是这样的......注意我现在还没有机会测试它。

Sub GetWidestShape()
        dim widest
        dim i as int;
        i=0

        for each shape in activesheet.shapes
          if(shape.width > widest.width or i =0) then
               widest = shape
          end if
          i++
        next
        'Do whatever you want with the shape.
        'you should be able to refrence the shape with the variable/object name "widest"
        'E.g range("a1").value=widest.width
end sub