2011-05-16 49 views
2

我目前正在處理幾個包含數百個複選框的工作表。這些複選框背後的代碼工作正常,但我正在尋找一種方法來列出每列的複選框名稱,例如,我需要知道列G中所有複選框的名稱。是否可以在Excel VBA中返回複選框的名稱?

有誰知道這是可能的嗎?

非常感謝!

回答

1

如果對齊控制列G(按住ALT鍵,同時移動對齊),選擇屬性,並找出控件的左側位置

然後,您可以使用此代碼來識別從Sheet1控制已經離開對齊等於你所需要的。

Sub test() 
lngcolumnGLeft = 288 'pseudo position of object aligned to column G 

'cycle through all objects 
With Sheet1 

    For Each obj In .OLEObjects 
     If obj.Left = lngcolumnGLeft Then 

      .Range("G" & .Rows.Count).End(xlUp).Offset(1, 0).Value = obj.Name 

     End If 
    Next obj 

End With 

End Sub 
2

如果您指定要檢查的列,下面的代碼將起作用。

舉例來說,如果你要搜索列E指定5所有複選框後的代碼檢查任何複選框即E列與列的最左邊部分的範圍內F.

Sub ListCheckBoxNames() 
    Dim col As Long, cb As OLEObject 

    col = 5 //e.g. A=1, B=2, C=3 etc...you need to change this as appropriate 

    For Each cb In Worksheets(1).OLEObjects 
     If cb.Left >= Columns(col).Left And cb.Left < Columns(col + 1).Left Then 
      Debug.Print cb.Name 
     End If 
    Next cb 
End Sub 
3

考慮使用TopLeftCell屬性

Sub ListCheckBoxes() 

    Dim ole As OLEObject 

    'Loop through all the active x controls 
    For Each ole In Sheet1.OLEObjects 
     'Only care about checkboxes 
     If TypeName(ole.Object) = "CheckBox" Then 
      'Check topleftcell property 
      If ole.TopLeftCell.Column = Sheet1.Range("G1").Column Then 
       'print out list 
       Debug.Print ole.TopLeftCell.Address, ole.Name 
      End If 
     End If 
    Next ole 

End Sub 
+0

我喜歡你已經使用'TypeName'和你TopLeftCell'的'使用方式。一個非常乾淨的解決方案,看起來很健壯 – 2011-05-17 18:03:00