如何解决在VBA中无效使用NULL

时间:2019-02-18 07:20:01

标签: excel vba

我正在使用vba脚本进行计算(只需加法)并在Excel用户窗体中显示值,但出现错误

  

运行时错误:94,无效使用Null

我试图将类型更改为float,但是仍然没有任何改进。

Private Sub submitmobile_Click()
    Dim i As Long, LastRow As Long
    LastRow = Sheets("Report").Range("A" & Rows.Count).End(xlUp).Row

    For i = 2 To LastRow
        If Sheets("Report").Cells(i, "A").Value = (Me.lst_Added) Or _
          Sheets("Report").Cells(i, "A").Value = Val(Me.lst_Added) Then
            Me.mobileutilize = Sheets("Report").Cells(i, "F").Value
            Me.mobilehours = Sheets("Report").Cells(i, "H").Value
        End If
    Next
End Sub

我希望输出应该显示在提到的文本框中(mobileutilize,mobilehours),其值应与工作表单元格中的值相同

1 个答案:

答案 0 :(得分:0)

我假设lst_Added是一个列表框。

因此,在使用它之前,请检查是否已选择某项。您可以通过

If lst_Added.Listindex = -1 Then
    Msgbox "Please select something"
    Exit Sub
End If

然后将您的代码用作

If Sheets("Report").Cells(i, "A").Value = lst_Added.Value....

您的代码可以写为(未经测试

Private Sub submitmobile_Click()
    Dim i As Long, LastRow As Long
    Dim lbValue As String
    Dim ws As Worksheet

    If lst_Added.ListIndex = -1 Then
        MsgBox "Please select something"
        Exit Sub
    End If

    '~~> Get value of the selected item in the listbox
    lbValue = lst_Added.List(lst_Added.ListIndex)

    Set ws = ThisWorkbook.Sheets("Report")

    With ws
        LastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To LastRow
            If .Cells(i, "A").Value = lbValue Or _
               .Cells(i, "A").Value = Val(lbValue) Then
                mobileutilize = .Cells(i, "F").Value
                mobilehours = .Cells(i, "H").Value
            End If
        Next
    End With
End Sub