Excel VBA将列表框值传递给sub

时间:2015-08-14 14:46:24

标签: excel vba

在尝试将userform列表框选择传递给sub时,我无法弄清楚我做错了什么。 scode变量没有从列表框选择中获取值(scode = ScrapReasonCodes.ListBox1.Value),因此无效使用null错误。

这是电子表格代码:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim rInt As Range
Dim rCell As Range
Set rInt = Intersect(Target, Range("a1:az40"))
 If Not rInt Is Nothing Then
    For Each rCell In rInt
        rCell.Value = "x"
    Next
 End If
Set rInt = Nothing
Set rCell = Nothing
Cancel = True
Call ScrapData
End Sub

Sub ScrapData()
Dim Stamp As String
Dim scode As String
Dim whereitat As String
whereitat = Selection.Address(False, False, xlA1)
Stamp = Format(Now(), "mm-dd-yyyy hh:nn:ss AM/PM")
'scode = InputBox("Issue Code")
ScrapReasonCodes.Show
scode = ScrapReasonCodes.ListBox1.Value
Sheets("Data").Select
ActiveCell.Offset(1, 0).FormulaR1C1 = Stamp
ActiveCell.Offset(1, 1).FormulaR1C1 = scode
ActiveCell.Offset(1, 2).FormulaR1C1 = whereitat
ActiveCell.Offset(1, 0).Select
Sheets("DWG").Activate
End Sub

这是用户表单和按钮代码

Sub CommandButton1_Click()
scode = ScrapReasonCodes.ListBox1.Value
' MsgBox (scode)
Unload Me

End Sub

Sub UserForm_Initialize()

Dim ScrapCodes As Range
Dim WS As Worksheet
Set WS = Worksheets("Data")
 For Each ScrapCodes In WS.Range("ScrapCodes")
    With Me.ListBox1
        .AddItem ScrapCodes.Value
    End With
 Next ScrapCodes

End Sub

谁能看到我哪里出错了?

1 个答案:

答案 0 :(得分:1)

问题是,当你单击CommandButton1_Click(我假设是接近或等)时,你卸载表单 - 这具有从内存擦除它的效果 - 然后当你实际重新初始化后执行此ScrapReasonCodes.ListBox1.Value表格(虽然没有显示表格)。为了解决这个问题,请隐藏如下所示的表单,读取您的值,然后从调用代码中卸载表单。

在ScrapData中更改以下两行

ScrapReasonCodes.Show
scode = ScrapReasonCodes.ListBox1.Value

以下三行

ScrapReasonCodes.Show
scode = ScrapReasonCodes.ListBox1.Value
unload ScrapReasonCodes

然后在您的用户窗体中,在CommandButton1_Click下面更改

Sub CommandButton1_Click()
scode = ScrapReasonCodes.ListBox1.Value
' MsgBox (scode)
Unload Me

End Sub

Sub CommandButton1_Click()
me.hide
End Sub