运行循环禁用控件时,Excel崩溃

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语句在第一行设置了一个断点,在它到达之前它仍然崩溃。 所以,我的另一个猜测是这是我的数组和/或变体定义的问题。

任何人有一个想法?

PS运行这段代码会导致你的Excel崩溃。

尝试这个:

 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 

当你像这样Dim的数组: iArray(5) ,你没有创build一个单一的元素数组5 。 你基本上是创build一个上限的项目放在数组内。 当你开始做iArray(x,y,z) ,你会混淆Excel,并要求它创build大量的具有疯狂上限的维度。

基本上,你创build数组错了。 以上应该工作。 像Split替代品也应该如此。 🙂

让我们知道这是否有帮助。

试试这个代码:

 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不会初始化包含值的数组期望,但是尝试创build15个dimime的arrays