Excel VBA对象帮助程序函数

时间:2015-08-11 13:05:18

标签: excel vba excel-vba

我有一个UserForm,其中一个ComboBox可以根据用户选择的其他变量而具有不同的值。我没有在每次用户进行更改时更新单个ComboBox的内容,而是创建了两个ComboBox,只需将相应的一个设置为可见。这两个ComboBox的名称为" width1_cb"和" width2_cb"分别

我创建了一个辅助函数来返回当前活动的ComboBox,以便我的其他代码可以使用它。这是辅助函数:

Function myGetActive(ByVal control As String) As ComboBox
If control = "width" Then
    If width1_cb.Visible = True Then
        Set myGetActive = Me.width1_cb
    ElseIf width2_cb.Visible = True Then
        Set myGetActive = Me.width2_cb
    Else
        Set myGetActive = Nothing
    End If
End If
End Function

不幸的是,此功能未按预期运行。我有另一行代码:

Set currentWidth = myGetActive("width")
currentWidth.Value = 5

在第二行失败。我无法弄清楚我在这里做错了什么 - 我最好的猜测是我在某种程度上没有在我的辅助函数中返回实际的组合框实例而是某种副本,但在我的研究中我无法弄清楚是否正确实现这一目标的方法。有没有人知道如何使这个功能按预期工作?

更新:我已经采取的调试工作,包括逐行逐步执行代码并放置" watch"在" myGetActive"在width1_cb和myGetActive变量上都有效。我发现myGetActive变量设置为" ComboBox / Combobox"而width1_cb是" Object / Combobox"。而且,width1_cb的上下文是" Input_Window.UserForm_Initialize"而myGetActive的上下文是" Input_Window.myGetActive"。该函数确实退出而没有任何错误。

1 个答案:

答案 0 :(得分:0)

最初我只是想对两种不同的方式发表评论来声明变量:

Private currentWidth As ComboBox

Private currentWidth As MSForms.ComboBox

但我无法复制你所遇到的问题。这是我用

测试的代码
Option Explicit

Private currentWidth  As ComboBox
'Private currentWidth  As MSForms.ComboBox

Private Sub UserForm_Click()
    testCombos
End Sub

Private Sub UserForm_Initialize()
    With Me.width1_cb
        .AddItem "test1"
        .AddItem "test2"
        .AddItem "test3"
    End With
    With Me.width2_cb
        .AddItem "test1"
        .AddItem "test2"
        .AddItem "test3"
    End With
End Sub

Private Sub testCombos()
    Set currentWidth = myGetActive("width")
    currentWidth.Value = 5
    Set currentWidth = myGetActive(vbNullString)
    currentWidth.Value = 7
End Sub
Function myGetActive(ByVal control As String) As ComboBox
    If control = "width" Then
        If width1_cb.Visible = True Then
            Set myGetActive = Me.width1_cb
        ElseIf width2_cb.Visible = True Then
            Set myGetActive = Me.width2_cb
        Else
            Set myGetActive = Nothing
        End If
    Else
        If width2_cb.Visible = True Then
            Set myGetActive = Me.width2_cb
        ElseIf width1_cb.Visible = True Then
            Set myGetActive = Me.width1_cb
        Else
            Set myGetActive = Nothing
        End If
    End If
End Function

enter image description here