2014-01-31 19 views
1
Public Sub OptionsDisable() 

    Dim myControls As CommandBarControls 
    Dim ctl As CommandBarControl 
    Dim iArray(21, 3181, 292, 3125, 855, 1576, 293, 541, 3183, 294, 542, 886, 887, 883, 884) As Long 
    Dim myElement As Variant 

    For Each myElement In iArray 
     Set myControls = CommandBars.FindControls _ 
      (Type:=msoControlButton, ID:=myElement) 
     If Not myControls Is Nothing Then 
      For Each ctl In myControls 
       ctl.Enabled = False 
      Next ctl 
     End If 
    Next 
End Sub 

好吧大家,當我運行這個子程序時,Excel只是崩潰。我試圖通過循環來禁用數組中的每個控件ID。我正在考慮發生了什麼,它正在進入一個無限循環,但是我在for語句的第一行設置了一個斷點,在它到達之前它仍然崩潰。所以,我的另一個猜測是這是我的數組和變體定義的問題。運行循環禁用控件時,Excel崩潰

任何人有想法?

P.S.運行此代碼會導致Excel崩潰。

回答

2

試試這個:

Public Sub OptionsDisable() 

Dim myControls As CommandBarControls 
Dim ctl As CommandBarControl 
Dim iArray As Variant 
Dim myElement As Variant 

iArray = Array(21, 3181, 292, 3125, 855, 1576, 293, 541, 3183, 294, 542, 886, 887, 883, 884) 

    For Each myElement In iArray 
     Set myControls = CommandBars.FindControls _ 
      (Type:=msoControlButton, ID:=myElement) 
     If Not myControls Is Nothing Then 
      For Each ctl In myControls 
       ctl.Enabled = False 
      Next ctl 
     End If 
    Next myElement 

End Sub 

當你這樣一個數組:iArray(5),你沒有創建一個單一元素的數組5。你基本上創建了一個上限的項目放入數組。當你開始做iArray(x,y,z)時,你會混淆Excel,並要求它創建很多具有瘋狂上限的維度。

基本上,你正在創建錯誤的數組。以上應該工作。像Split這樣的替代品也應該如此。 :)

讓我們知道這是否有幫助。

+0

這工作,謝謝。 – ilarson007

3

試試這個代碼:

Public Sub OptionsDisable1() 

    Dim myControls As CommandBarControls 
    Dim ctl As CommandBarControl 
    Dim iArray As Variant 
    Dim myElement As Variant 

    iArray = Array(21, 3181, 292, 3125, 855, 1576, 293, 541, 3183, 294, 542, 886, 887, 883, 884) 

    For Each myElement In iArray 
     Set myControls = CommandBars.FindControls _ 
      (Type:=msoControlButton, ID:=myElement) 
     If Not myControls Is Nothing Then 
      For Each ctl In myControls 
       ctl.Enabled = False 
      Next ctl 
     End If 
    Next 
End Sub 

當你使用Dim iArray(21, 3181, 292, 3125, 855, 1576, 293, 541, 3183, 294, 542, 886, 887, 883, 884) As Long像您期望的Excel不初始化值的數組,而是嘗試與15個dimmensions創建陣列

+1

+1:我太懶了。 :D – Manhattan

+1

...這是一個巨大的陣列!如果可以創建它,它將總共包含'Long'類型的'4 * 10^42'變量(每個8個字節)。 – Taosique