Vlookup 类型不匹配

Vlookup type mismatch

我正在尝试在 VBA 中执行 vlookup,代码似乎没有正确获取单元格值。变量 rowrng 和 colrng 返回为 #N/A

  Sub DosiDo()

'Declare Variables
Dim colnum As Long
Dim rownum As Long
Dim i As Integer
Dim rowrng As Variant
Dim colrng As Variant

'Set worksheets
Dim wb As Workbook
Dim ws As Worksheet
Dim newWs As Worksheet
Dim table1 As Range
Dim ws1 As String

Set wb = ActiveWorkbook
Set newWs = wb.Worksheets.Add
newWs.Name = "DosiDo"

    
    With Workbooks("210721-LeaveRecords.xlsm").Sheets("Sheet1")
            Set table1 = .Range(.Cells(2, 2), .Cells(7, 9))
    End With

    wsl = "AS Darwin"

    rowrng = Application.VLookup(ws1, table1, 7, False)
    colrng = Application.VLookup(ws1, table1, 8, False)
    
    newWs.Cells(i + 1, 4).Value = rowrng
    newWs.Cells(i + 1, 5).Value = colrng

End Sub

你暗ws1错了

ws1更改为wsl

  Sub DosiDo()

'Declare Variables
Dim colnum As Long
Dim rownum As Long
Dim i As Integer
Dim rowrng As Variant
Dim colrng As Variant

'Set worksheets
Dim wb As Workbook
Dim ws As Worksheet
Dim newWs As Worksheet
Dim table1 As Range
Dim wsl As String

Set wb = ActiveWorkbook
Set newWs = wb.Worksheets.Add
newWs.Name = "DosiDo"

    
    With Workbooks("210721-LeaveRecords.xlsm").Sheets("Sheet1")
            Set table1 = .Range(.Cells(2, 2), .Cells(7, 9))
    End With

    wsl = "AS Darwin"

    rowrng = Application.VLookup(ws1, table1, 7, False)
    colrng = Application.VLookup(ws1, table1, 8, False)
    
    newWs.Cells(i + 1, 4).Value = rowrng
    newWs.Cells(i + 1, 5).Value = colrng

End Sub

N/A 当 VLOOKUP 在最后一个参数为“FALSE”时提供的范围的第一列中找不到键值时的结果。也许这就是问题所在??

Table1 地址是 $B$2:$I$7。您的 VLOOKUP 函数分别从 $H$2:$H$7 和 $I$2:$I$7 中为 $B$2:$B$7 中具有“AS Darwin”的行查找值。这就是你想要的吗?

如果是这样,也许您可​​以尝试使用 AutoFilter?

With table1
    .AutoFilter Field:=1, Criteria1:=ws1, Operator:=xlAnd
    .SpecialCells(xlCellTypeVisible).Areas(2).Resize(1, 2).Offset(, 5).Copy NewWS.Cells(i + 1, 4)
    .AutoFilter 'turns autofilter off
End With

如果 table1 未格式化为 Excel Table(VBA“ListObject”),则需要 .Areas(2),并且如果匹配row 不是 headers 之后的第一行(第 3 行)。此外,.Resize(1, 2) returns 仅匹配第一行的两列,并且从 table 左侧的第 6 列开始(.Offset(, 0) = 本中的 B 列例)。

对于过滤器后没有可见行的情况(例如,If .SpecialCells(xlCellTypeVisible).Rows.Count > 1 or .SpecialCells(xlCellTypeVisible).Areas.Count > 1 Then ...),您需要进行补漏白