0

这有效 Lastrow = 8,但不是 9(类型不匹配)

如果我删除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
4

4 回答 4

3

MyArray 采用 2 种不同的类型,具体取决于给定的范围。
如果您正在查看 1 个单元格,那么它是一个变体(如果它是空的则可以测试)
如果您正在查看 2 个或更多单元格,那么它会变成一个变体数组,因此您必须测试每个单元格.

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

测试,使用:

if vartype(myarray)=vbArray then
    ' run through the array
else
    ' do single value stuff
endif
于 2012-06-28T15:02:06.763 回答
1

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

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

但我也认为还有另一种方法可以做你想做的事。稍微简单一点,并使用内置函数。我想我在这里抓住了你的意图:

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
于 2012-06-28T17:31:53.083 回答
1
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
于 2012-06-28T17:54:46.707 回答
0
myarray = Sheets(SheetName).Range("d8:d" & LastRow)

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

我想它可以像这样简单,不......?

于 2012-06-28T15:17:52.993 回答