从Excel宏中获取Userform到Module的值

时间:2017-10-24 15:29:32

标签: excel vba excel-vba

我在SQL方面有一定的知识,能够管理简单的查询......

基本意图是在我创建的Excel宏上添加一个下拉列表(而不是用户提供他想要的任何值的文本框)但经过大量研究后我才知道只有Userform可以帮助我满足我的要求,现在我想知道如何在一个模块下提供在Userform下选择的值,以便我可以将从下拉列表中选择的那些值用于任何其他目的。我创建了一个带有以下代码的示例用户表单

USER-FORM

Private Sub cmdAdd_Click()
  Call Try1
  Unload Me
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)

  If CloseMode = vbFormControlMenu Then
    Cancel = True
    MsgBox "Please use the Close Form button!"
  End If
End Sub

Private Sub UserForm_Initialize()
    Dim cPart As Range
    Dim cLoc1 As Range
    Dim ws As Worksheet
    Set ws = Worksheets("LookupLists")

    For Each cPart In ws.Range("PartIDList")
        With Me.cboPart
            .AddItem cPart.Value
            .List(.ListCount - 1, 1) = cPart.Offset(0, 1).Value
        End With
    Next cPart

    For Each cLoc1 In ws.Range("LocationList")
        With Me.cboLocation
            .AddItem "Cluster1"
            .AddItem "Cluster2"
            .AddItem "Location 3"
        End With
    Next cLoc1

    Me.txtDate.Value = Format(Date, "Medium Date")
    Me.txtQty.Value = 1
    Me.cboPart.SetFocus

End Sub

模块

Sub Rectangle1_Click()
    frmPartLoc.Show
End Sub

Sub Try1()
    Dim Location
    Location = cboLocation.Value
    Part = cboPart.Text
    MsgBox Location.Value
    MsgBox Part.Text
End Sub

实际上这段代码在这里有一些问题

"Location = cboLocation.Value   Part = cboPart.Text"

我想可以在我们使用USER-FORM选择的MODULE上获取值。但我对我的代码有一些错误,或者对这些东西的理解有所不同。请帮我纠正我的代码。

如果您想要use this link获取相同的zip文件,或者您可以使用以下链接浏览

http://www.contextures.com/xlUserForm01.html

先谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

感谢Tigeravatar帮助找到解决方案。

我们必须在组合框名称之前提及USER-FORM名称,我们从USER-FORM填充这些名称。

请在下面找到更正后的代码

Sub Try1()
    Dim Location
    Location = frmPartLoc.cboLocation.Value
    Part = frmPartLoc.cboPart.Value
    MsgBox Location
    MsgBox Part
End Sub

再次感谢所有评论