clsCommandButton:Microsoft Excel VBA - 运行时错误'-2147024809(80070057)'

时间:2018-03-12 10:09:09

标签: vba excel-vba excel

我想在For-Loop中动态地将CommandButtons添加到我的Userform。如何在For-Loop中添加新的CommandButtons?

 Dim CommandButtons(5) As clsCommandButtons
    Private Sub UserForm_Initialize()
    Dim zaehler As Integer
    For zaehler = 0 To 4
        Set CommandButtons(zaehler) = New clsCommandButtons
        Set CommandButtons(zaehler).cmdCommandButton = Me.Controls(zaehler)
        Next
    End Sub

这是我的班级:

Option Explicit

Public WithEvents cmdCommandButton As CommandButton

Private Sub cmdCommandButton_Click()
    Dim sFilepath       As String                       

    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .InitialFileName = ActiveWorkbook.Path & "\"
        .Filters.Add "TextFiles", "*.txt", 1
        .FilterIndex = 1
        If .Show = -1 Then
            sFilepath = .SelectedItems(1)
        End If
    End With

    Cells(c_intRowFilterPathStart, c_intClmnFilterPath) = sFilepath
End Sub

我不知道如何处理此错误。我该如何解决这个问题?

4 个答案:

答案 0 :(得分:0)

我认为您收到错误是因为您正在访问不存在的控件。请注意,控件从0计算到Me.Controls.count-1,因此您的问题可能已解决

Set CommandButtons(zaehler).cmdCommandButton = Me.Controls(zaehler-1)

但我想更好的解决方案是命名按钮并按名称分配:

 Set CommandButtons(zaehler).cmdCommandButton = Me.Controls("CommandButton" & zaehler)

答案 1 :(得分:0)

CommandButtons集合定义为Variant

  • Dim CommandButtons(15) As Variant,而不是Dim CommandButtons(15) As clsCommandButtons

在这个Variant中,你会放置你的CommandButtons。这是一些最小的代码,可以帮助您了解我的意思:

CustomClass

Private Sub Class_Initialize()
    Debug.Print "I am initialized!"
End Sub

In a module

Private SomeCollection(4) As Variant    
Public Sub TestMe()        
    Dim cnt As Long
    For cnt = 1 To 4
        Set SomeCollection(cnt) = New CustomClass
    Next cnt        
End Sub

从这个小的运行代码中,您可以进一步开始调试:)

答案 2 :(得分:0)

Dim a() As clsCommandButton

Private Sub UserForm_Initialize()

Dim c As Control

On Error GoTo eHandle

For Each c In Me.Controls
    If TypeName(c) = "CommandButton" Then
        ReDim Preserve a(UBound(a) + 1)
        Set a(UBound(a)) = New clsCommandButton
        Set a(UBound(a)).cmd = c
    End If
Next c

Exit Sub

eHandle:

    If Err.Number = 9 Then
        ReDim a(0)
    End If

    Resume Next

End Sub

使用以下课程

Public WithEvents cmd As commandbutton

Private Sub cmd_Click()
    MsgBox "test"
End Sub

答案 3 :(得分:0)

我认为您的问题出现在Me.Controls(zaehler)部分。 zaehler从1开始,但Me.Controls(...)从0开始。

Set CommandButtons(zaehler).cmdCommandButton = Me.Controls(zaehler - 1)

可能会解决它