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

时间:2014-01-31 14:06:36

标签: excel vba excel-vba

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

有人有想法吗?

P.S。运行此代码会导致Excel崩溃。

2 个答案:

答案 0 :(得分: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 :(得分: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

当您Dim这样的数组:iArray(5)时,您并未创建包含单个元素5的数组。您基本上创建了要放入数组的项目的上限。当您开始执行iArray(x,y,z)时,您会混淆Excel并要求它创建大量具有疯狂上限的维度。

基本上,您创建的数组错误。以上应该有效。像Split这样的替代品也应如此。 :)

如果有帮助,请告诉我们。