VBA:运行时错误 9 - 似乎无法在同一用户窗体代码模块中找到公共函数



这是我正在构建的用户窗体的代码,一切都通过测试数组顺利运行。

我正在寻找与公共函数 GetMatchingArt 的部分匹配,这本身很好,为每个匹配添加一个OptionButton

但是当我尝试在UserForm_Initialize调用此函数时,它会系统地给我运行时错误 9(下标超出范围)。

这意味着它找不到该功能,尽管它是公共的,即使它们在同一个模块(UF 的代码模块)中。

UserForm_Initialize,我似乎找不到调用我的函数的方法......

Private Opt As MSForms.OptionButton
Private Prod()
Private Stock()

Private Sub UserForm_Initialize()
Dim MaxWidth As Long, _
    TotalHeight As Long, _
    A()
MaxWidth = 0
'Add_Options (Split("test1,test2,test3,test4,test5,test6,test7", ","))
'Call GetMatchingArt
'A = GetMatchingArt()
'Add_Options A
'Add_Options GetMatchingArt
Add_Options GetMatchingArt()


For i = 0 To UF_Prod.Controls.Count - 1
    If UF_Prod.Controls(i).Width > MaxWidth Then MaxWidth = UF_Prod.Controls(i).Width
    TotalHeight = TotalHeight + UF_Prod.Controls(i).Height * 11 / 10
Next i
Me.Height = TotalHeight
Me.Width = MaxWidth * 12 / 10
If Me.CommandButton1.Width >= MaxWidth Then Me.CommandButton1.Width = 6 * MaxWidth / 10
Me.CommandButton1.Top = Me.Height - Me.CommandButton1.Height * 7 / 4
Me.CommandButton1.Left = (Me.Width - Me.CommandButton1.Width) / 2
MsgBox "UF ready", vbinfo, "Loaded UF"
End Sub

这是函数:

Public Function GetMatchingArt() As Variant
LoadInfo
Dim cVal As String, _
    A() 
cVal = ActiveCell.Value2
For i = LBound(Prod, 1) To UBound(Prod, 1)
    If InStr(1, Prod(i, 1), cVal) Then
        A(UBound(A)) = Prod(i, 1)
        ReDim Preserve A(UBound(A) + 1)
    Else
        'No match
    End If
Next i
ReDim Preserve A(UBound(A) - 1)
GetMatchingArt = A
End Function

我使用的其余代码(没有问题):

Public Sub LoadInfo()
    Prod = Sheets("Products").UsedRange.Value2
    Stock = Sheets("Stock").UsedRange.Value2
End Sub

Sub Add_Options(ByVal Arr As Variant)
For i = LBound(Arr) To UBound(Arr)
    Set Opt = UF_Prod.Controls.Add("Forms.optionButton.1", "Opt" & i, True)
    With Opt
        .Caption = Arr(i)
        .Top = Opt.Height * Int((i + 1) / 2)
        .Left = 10 + (Int((i + 1) / 2) * 2 - i) * UF_Prod.Width / 2
    End With
    Set Opt = Nothing
Next i
End Sub

感谢您的帮助! :)

从我所看到的快速浏览您的代码。您正在尝试在初始事件中添加新的选项按钮。据我所知,你不能这样做,因为在真正启动任何东西之前就调用了代码。尝试将代码放入激活而不是初始化

原来你可以在初始化中插入按钮。但是,此代码没有,并且适用于激活事件。因此,代码中的某些内容试图使用尚未初始化的内容。

最新更新