VBA:运行时错误9 – 似乎无法find在同一个UserForm代码模块中的公用function

这里是我build立的用户窗体的代码,一切运行顺利与testingarrays。

我正在寻找与公共函数GetMatchingArt的部分匹配,这是他自己的罚款,为每个比赛添加一个OptionButton

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

意思是它找不到这个函数,尽pipe它是Public的 ,即使它们在同一个模块 (UF的Code模块)中。

UserForm_Initialize ,我似乎无法find一种方式来调用我的function…

 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 

这是function:

 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 

谢谢你的帮助! 🙂

从我可以看到你的代码快速查看。 您正试图在initalize事件中添加一个新的选项button。 据我所知,你不能这样做,因为在任何事情真正起作用之前,代码被调用。 尝试把代码激活而不是初始化

编辑。 原来你可以在initalize中插入button。 但是这个代码并没有在activate事件上工作。 所以在代码中的东西是试图使用一些没有被初始化的东西。