首页 > 解决方案 > 如何在 VBA 中查找另一个 Excel 工作表

问题描述

Sub lookuphcpcs()

On Error GoTo errorbox:
Dim hcpcs_code As Long

Dim desc As Variant
hcpcs_code = ActiveCell.Value

If Len(hcpcs_code) > 0 Then
    desc = Application.WorksheetFunction.VLookup(Active_cell, 'C:\Users\Username\Desktop\[Fruit Code.xlsx]Sheet1'!$A$2:$B$7, 2, False)
    MsgBox "Description for HCPCS Code " & hcpcs_code & " is """ & desc & """"

Else
    MsgBox "You did not enter any input!"    
End If

Exit Sub

errorbox:
If Err.Number = 1004 Then
    MsgBox "No Description found under HCPCS list!"
End If

End Sub

我无法将表数组值放在 VBA 中的 Vlookup 下以指向另一个 Excel 表。

我怎么做?

标签: vbaexcel

解决方案


首先,当Vlookup您需要处理错误时,例如Vlookup无法找到匹配项时,您可以使用它If Not IsError(Application.VLookup(....来实现这一点。

其次,在你的情况下你不需要使用On Error GoTo errorbox:,只需使用Vlookup我在第一点写的错误处理。

第三,您可以If Trim(ActiveCell.Value2) <> "" Then用来验证里面是否有有效的文本或数字,ActiveCell而不是空格。

第四,你应该避免使用ActiveCell, 而是使用完全限定的对象。

最后,您要确保"Fruit Code.xlsx"在使用之前打开工作簿Vlookup,正如@Tim Williams 在上面的评论中所建议的那样。

修改后的代码

Option Explicit

Sub lookuphcpcs()

Dim desc As Variant
Dim SourceWb As Workbook

' error trapping in case Fruit Code workbook is closed
On Error Resume Next
Set SourceWb = Workbooks("Fruit Code.xlsx")
On Error GoTo 0
If SourceWb Is Nothing Then
    Set SourceWb = Workbooks.Open("C:\Users\Username\Desktop\Fruit Code.xlsx") ' open workbook if it's closed
End If

If Trim(ActiveCell.Value2) <> "" Then ' make sure cell has a string other than space
    If Not IsError(Application.VLookup(ActiveCell.Value2, SourceWb.Sheets("Sheet1").Range("A2:B7"), 2, 0)) Then
        desc = Application.VLookup(ActiveCell.Value2, SourceWb.Sheets("Sheet1").Range("A2:B7"), 2, 0)
        MsgBox "Description for HCPCS Code " & ActiveCell.Value2 & " is """ & desc & """"
    Else
        MsgBox "No Description found under HCPCS list!"
        Exit Sub
    End If
Else
    MsgBox "You did not enter any input!"
End If

End Sub

推荐阅读