vba - 如何在 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 表。
我怎么做?
解决方案
首先,当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
推荐阅读
- google-apps-script - 谷歌表格中的谷歌脚本,是否允许所有用户?
- android - android - 使用 Kotlin 协程实现房间
- javascript - 条件语句中的空返回语句如何起作用?
- reactjs - 谷歌图表如何在 React 中选择后保持十字准线
- r - R 使用哪种算法来计算一类 SVM?(包 e1071)
- react-native - 父视图不跟随其高度
- c# - 为什么调用Web服务时返回的日期为“0001-01-01”?
- android - CardView 依赖链接失败
- angular - 如何将 ng serve 用于角度库?
- python - Python正则表达式检查两个离散值的字符串长度