Search code examples
vbaexceltype-mismatchmismatch

Type mismatch VBA


This works Lastrow = 8, but not 9 (Type mismatch)

If i remove If Not (myarray = Empty) Then it does not work for 8

What is the easiest way to solve this?

Public Function GetRowToWriteOn(ByVal SheetName As String, ByVal idnr As Integer) As Integer
    LastRow = (Sheets(SheetName).UsedRange.Rows.Count) + 1
    MsgBox (LastRow)
    myarray = Sheets(SheetName).Range("d8:d" & LastRow).Value
    If Not (myarray = Empty) Then
        For row = 1 To UBound(myarray, 1)
            If (myarray(row, 1) = idnr) Then
                GetRowToWriteOn = row
                Exit Function
            End If
        Next
    End If
    GetRowToWriteOn = LastRow
    Exit Function
End Function

Solution

  • MyArray is taking 2 different types, depending on the range given.
    If you are looking at 1 cell, then it is a single variant (which can be tested if it is Empty)
    If you are looking at 2 or more cells, then it becomes an array of variant, so you would have to test each cell.

    myarray = Sheets(SheetName).Range("d8:d8").Value - myarray gets the value in d8
    myarray = Sheets(SheetName).Range("d8:d9").Value - myarray(1,1) gets the value in d8, and myarray(2,1) gets the value in d9

    to test, use:

    if vartype(myarray)=vbArray then
        ' run through the array
    else
        ' do single value stuff
    endif