2013-04-10 133 views
0

我想通過大量工作表循環,然後在每個工作表中填充列表框控件,並用我的代碼填充它們。我使用下面的代碼:Excel VBA - 通過ListBox控件循環

Dim sh As Worksheet 
Dim obj As OLEObject 
Dim lst As MSForms.ListBox 
Dim idx As Long 

For idx = 1 To ThisWorkbook.Worksheets.Count 
    Set sh = ThisWorkbook.Worksheets(idx) 
    For Each obj In sh.OLEObjects 
     If obj.progID = "Forms.ListBox.1" Then 
      Set lst = obj 
      If (lst.Name = "lst1") Then 
       Call PopulateSimple(lst, "Table1") 
      End If 
     End If 
    Next 
Next idx 

這似乎是不幸的,當我將列表框設置爲對象。任何想法如何實現循環遍歷不同工作表中的所有列表框並填充它們?

+0

你需要什麼參考? 'MSForms.ListBox'給了我一個編譯錯誤,「用戶定義類型無法識別」 – 2013-04-10 14:54:20

+0

無視,我找到了MS Forms庫的引用。當我運行這個代碼時,sh.OLEObjects是空的。你如何插入ListBox控件? – 2013-04-10 14:55:48

+2

在我看來,你需要將'Dim lst as MSForms.ListBox'改成'Dim lst as OLEObject',這就是所有... – 2013-04-10 14:57:32

回答

2

試試這個

Sub Sample() 
    Dim sh As Worksheet 
    Dim obj As OLEObject 
    Dim idx As Long 

    For idx = 1 To ThisWorkbook.Worksheets.Count 
     Set sh = ThisWorkbook.Worksheets(idx) 
     For Each obj In sh.OLEObjects 
      If TypeOf obj.Object Is MSForms.ListBox Then 
       If (obj.Name = "lst1") Then 
        Call PopulateSimple(obj, "Table1") 
       End If 
      End If 
     Next 
    Next idx 
End Sub 

說明:你得到的是錯誤的,因爲OBJ被聲明爲OLEObject和LST爲MSForms.ListBox,因此類型不匹配。

+0

你打我3秒左右! – 2013-04-10 15:02:01

+0

感謝,似乎解決它。 – Dimitris 2013-04-10 15:02:05

+0

@菲利普:謝謝菲利普:) 3秒? 4分鐘你的意思是? ;) – 2013-04-10 15:03:19

0

不能使用OBJ在您的來電PopulateSimplesince你知道這是一個ListBox:

Dim sh As Worksheet 
Dim obj As OLEObject 
Dim lst As MSForms.ListBox 
Dim idx As Long 

For idx = 1 To ThisWorkbook.Worksheets.Count 
    Set sh = ThisWorkbook.Worksheets(idx) 
    For Each obj In sh.OLEObjects 
     If obj.progID = "Forms.ListBox.1" Then 
      'Set lst = obj 
      If (obj.Name = "lst1") Then 
       Call PopulateSimple(obj, "Table1") 
      End If 
     End If 
    Next 
Next idx 
0

最簡單的方法(從評論移動):

在我看來,你需要改變

Dim lst as MSForms.ListBox 

Dim lst as OLEObject 

這就是所有...