VBA 处理多个文件时出现 VLOOKUP 错误 'Type mismatch'

VBA VLOOKUP error 'Type mismatch' when working with multiple files

我正在尝试创建一个将打开 2 个文件的宏,从第一个文件中获取一个 ID(ID 代表 K 列,每个元素行都有一个 ID),在第二个文件中使用 VLOOKUP 进行搜索,复制同一行、W 和 X 列的值并将它们粘贴到第一个文件的 W 和 X 列中。

这是我尝试过的:

Dim position As String
Dim last_y As Long
Dim matrix As String
Dim w_value As Variant

Workbooks(first_file_name_without_path).Activate
ActiveWorkbook.Sheets(1).Activate

For i = 3 To ActiveWorkbook.Sheets(1).UsedRange.Rows.Count
        
        Dim test As String
        position = "K" & CStr(i)
        'tried a different approach with this variable but without success'
        test = Trim(ActiveWorkbook.Sheets(1).Range(position))
        
        
        Workbooks(second_file_name_without_path).Activate
        ActiveWorkbook.Sheets(1).Activate
        
        last_y = ActiveWorkbook.Sheets(1).UsedRange.Rows.Count
        matrix = "K" & "3" & ":W" & CStr(last_y)
        'MsgBox (matrix)'
        w_value = Application.VLookup(ActiveWorkbook.Sheets(1).Cells(i, "K"), ActiveWorkbook.Sheets(1).Range(matrix), 23, False)
        'Error here, further code will be added later'
        MsgBox (w_value)
Next i

我已经检查了大部分存在的帖子,但找不到我的错误。我完全迷路了。

您的 VLookup 将始终 return 一个错误,因为您要求获取只有 13 列 (K:W) 的范围的第 23 列。如果你想returnW列的值,你需要13作为第三个参数(因为W列是范围的第13列)。
您看到的类型不匹配来自 MsgBox-命令,因为 w_value 包含 Error 2023,这不是字符串而是特殊数据类型(不能用作 [=12 的参数) =])

但是,你的代码问题比较多,主要原因是你使用了ActiveWorksheetActivate。您的 Vlookup 不会在第二个 sheet 中搜索您第一个 sheet 的值,因为您搜索 ActiveWorkbook.Sheets(1).Cells(i, "K") 但已经激活了第二个 sheet.

在编程VBA的几乎所有情况下,都不需要使用activateselect,并且应该避免使用ActiveSheetSelection。阅读 How to avoid using Select in Excel VBA 了解更多信息

我也替换了 UsedRange 的用法,因为它并不总是可靠的。参见 Error in finding last used cell in Excel with VBA

看看下面的代码:

Dim searchRange As Range
With Workbooks(second_file_name_without_path).Sheets(1)
    Dim last_y As Long
    last_y = .Cells(.Rows.Count, "K").End(xlUp).row
    Set searchRange = .Range("K3:W" & last_y)
End With
  
With Workbooks(first_file_name_without_path).Sheets(1)

    Dim lastRow As Long
    lastRow = .Cells(.Rows.Count, "K").End(xlUp).row

    Dim i As Long
    For i = 3 To lastRow
        Dim searchVal
        searchVal = .Cells(i, "K")
        Dim w_value As Variant
        w_value = Application.VLookup(searchVal, searchRange, 13, False)
        If IsError(w_value) Then
            MsgBox "An error occurred looking for " & searchVal & vbCrLf & CStr(w_value)
        Else
            MsgBox w_value
        End If
    Next i
End With