types不匹配VBA

这工作拉斯特罗= 8,但不是9(types不匹配)

如果我删除If Not (myarray = Empty) Then它不适用于8

什么是解决这个最简单的方法?

 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 

MyArray采取2种不同的types,取决于给定的范围。
如果您正在查看1个单元格,那么它是一个单独的变体(可以testing它是否为空)
如果您正在查看2个或更多个单元格,则会变成一个变体arrays,因此您必须testing每个单元格。

myarray = Sheets(SheetName).Range("d8:d8").Value – myarray得到d8的值
myarray = Sheets(SheetName).Range("d8:d9").Value – myarray(1,1)获取d8中的值,myarray(2,1)获取d9中的值

testing,使用:

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

我觉得你的代码应该看起来更像这样

 Option Explicit Public Function GetRowToWriteOn(ByVal SheetName As String, ByVal idnr As Integer) As Integer Dim lastrow As Long, row As Long lastrow = (Sheets(SheetName).UsedRange.Rows.Count) + 1 MsgBox (lastrow) Dim myarray() As Variant myarray = Sheets(SheetName).Range("d8:d" & lastrow).Value If Not (IsEmpty(myarray)) 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 

但我也认为有另一种方式来做你想做的事情。 有点简单,使用内置的function。 我想我在这里抓住你的意图:

 Dim RowToWriteOn As Long, SheetName As String, lastRow As Long Dim rng As Range SheetName = "Sheet1" lastRow = (Sheets(SheetName).UsedRange.Rows.Count) + 1 Set rng = Sheets(SheetName).Range("d" & lastRow) RowToWriteOn = rng.End(xlUp).row 
 Public Function GetRowToWriteOn(ByVal SheetName As String, _ ByVal idnr As Integer) As Long Dim lastRow As Long, f As Range lastRow = Sheets(SheetName).Cells(Rows.Count, 4).End(xlUp).Row Set f = Sheets(SheetName).Range("D8:D" & lastRow).Find(what:=idnr, _ lookat:=xlWhole) If Not f Is Nothing Then GetRowToWriteOn = f.Row Else GetRowToWriteOn = lastRow + 1 End If End Function 
 myarray = Sheets(SheetName).Range("d8:d" & LastRow) 

(没有价值)…你可以使用: if ubound(myArray) > 1 then ;..

我认为这可能是这样容易,不… …?