簡體   English   中英

如何在VBA中Vlookup另一個Excel工作表

[英]How to vlookup another excel sheet in VBA

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工作表。

我怎么做?

首先 ,在使用Vlookup時,您需要處理錯誤,例如當Vlookup無法找到匹配項時,可以使用If Not IsError(Application.VLookup(....實現此目的。

其次 ,在您的情況下,您無需使用On Error GoTo errorbox:只需使用我在第一點中編寫的Vlookup錯誤處理即可。

第三 ,可以使用If Trim(ActiveCell.Value2) <> "" Then驗證ActiveCell內是否有有效的文本或數字,而不是空格。

第四 ,應避免使用ActiveCell ,而應使用完全合格的對象。

最后 ,您要確保在使用Vlookup之前已打開"Fruit Code.xlsx"工作簿,如@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM