简体   繁体   中英

How to solve Invalid use of NULL in vba

I am using vba script to calculate(Just addition) and display the values in Excel Userform, but I am getting the error

Runtime error:94, Invalid use of Null

I tried to change the type to float, but still no improvements.

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

I expect the output should be displayed in the textboxes mentioned (mobileutilize, mobilehours) with the value as it is in sheet cells

I am assuming the lst_Added is a Listbox.

So before using it, check if something is selected or not. You can do that by

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

Then use your code as

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

Your code can be written as ( Untested )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM