2017-08-24 99 views
0

我剛剛開始在Word 2007(Office XP)中使用VBA,我嘗試創建循環以遍歷所有工具欄和每個工具欄中包含的所有按鈕。VBA For .. Next循環試圖通過工具欄按鈕

我做了這個代碼

Public Sub PasteFromClipboard() 
    Dim i As Long 
    Dim j As Long 
    Dim sCmdBar As CommandBar 

     Dim thisCommandBar As CommandBar 
     Dim thisCommandButton As CommandBarButton 

    Debug.Print "Number", "Name", "Visible", "Built-in" 
    For i = 1 To Application.CommandBars.Count 
    Set sCmdBar = Application.CommandBars(i) 
    If sCmdBar.Visible = True Then 
     j = j + 1 
     Debug.Print j, sCmdBar.Name, sCmdBar.Visible, sCmdBar.BuiltIn 

     Dim X As Long 
     Set thisCommandBar = Application.CommandBars(sCmdBar.Name) 
     For X = 1 To thisCommandBar.Controls.Count - 1 
      Set thisCommandButton = thisCommandBar.Controls(X) 
      If thisCommandButton.Caption = "Paste" Then 
       Dim a As Long 
       a = a + 1 
       Exit For 
      End If 
     Next X 

    End If 
    Next i 

但我得到運行時錯誤13:類型不匹配以下行:

Set thisCommandButton = thisCommandBar.Controls(X).

爲什麼出現這種情況,如何糾正呢?

還有一個問題。是否有可能以某種方式更改條件,以便在使用本地語言編寫代碼時查找按鈕的標題?不是英文。在我使用的Word中,在剪貼板窗格中,有按鈕標題爲「Vložitvše」(全部插入)和「Vymazatvše」(全部刪除)和「Možnosti」(選項)。我想找到包含這三個按鈕的工具欄(但肯定我不知道真正的英文字幕)。

回答

1

我必須讓它工作使用每個

Dim i As Long 
    Dim j As Long 
    Dim sCmdBar As CommandBar 

     Dim thisCommandBar As CommandBar 
     Dim thisCommandButton As CommandBarButton 

    Debug.Print "Number", "Name", "Visible", "Built-in" 
    For i = 1 To Application.CommandBars.Count 
    Set sCmdBar = Application.CommandBars(i) 
    If sCmdBar.Visible = True Then 
     j = j + 1 
     Debug.Print j, sCmdBar.Name, sCmdBar.Visible, sCmdBar.BuiltIn 

     Set thisCommandBar = Application.CommandBars(sCmdBar.Name) 
     For Each Ctl In thisCommandBar.Controls 
      If Ctl.Caption = "Paste" Then 
       Dim a As Long 
       a = a + 1 
       Exit For 
      End If 
     Next 

    End If 
    Next i 
+0

性能技巧:外環也應該是'對於Each'循環。你正在迭代一個對象集合,使用'For Each'循環。當你迭代數組時,使用'For ... Next'循環。 –

+0

這只是一個測試代碼。我沒有專注於表演或漂亮的風格。我只想做一個簡單的代碼來搜索工具欄...... – user1141649

+0

當你開始意識到通過一個'For'循環而不是'For Each'循環通過索引來迭代一個對象集合運行速度慢了27倍,也許它會沉入水中。 –