VBA:运行时错误9 - 似乎它无法在同一个UserForm代码模块中找到公共功能

时间:2015-04-30 08:29:39

标签: excel vba excel-vba userform

以下是我构建的UserForm的代码,所有内容都可以通过测试数组顺利运行。

我正在寻找与公共函数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

感谢您的帮助! :)

1 个答案:

答案 0 :(得分:1)

从我看到的内容可以快速查看代码。您正尝试在initalize事件中添加新选项按钮。据我所知,你无法做到这一点,因为代码在任何事情真正被初始化之前被调用。尝试将代码置于激活而不是初始化

EDIT。事实证明,您可以在initalize中插入按钮。但是,此代码没有并且对activate事件起作用。所以代码中的某些东西试图使用尚未初始化的东西。

相关问题