如何在VBA中Vlookup另一个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工作表。

我怎么做?

Shai Rado

首先,当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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在另一个工作表中查找数据并使用excel VBA替换相应的值

参考另一个工作表VBA在Excel中重命名工作表

如何通过另一个工作簿中的 VBA 对象名称引用 Excel 工作表?

Excel / VBA如何在上次使用的单元格之后将数据从一个工作表移动到另一个工作表?

如何过滤表格并将值粘贴到 Excel VBA 中的另一个工作表中

VBA VLookup 来自另一个关于单元格更改的 VBA 工作表

如何从Module-Excel VBA中的另一个工作表引用单元格?

如果值匹配,如何复制并粘贴到另一个工作表-Excel VBA

如何在一个工作表的Excel单元格中转换值以在另一个工作表中显示为下拉列表

Excel VBA:从另一个工作表中的URL显示图像

在另一个工作表中粘贴单元格的位置 - Excel VBA

Excel VBA中的循环列引用更改为另一个工作表

输入表格,Excel,VBA复制输入并粘贴到另一个工作表中

如何在Excel中自动将列值填充到另一个工作表中?

在Excel中添加另一个工作表

我如何在excel中将范围从一个工作簿复制到另一个工作簿而不必在VBA中命名呢?

Excel VBA如何在工作表中找到最佳价格并将所有行放入另一个工作表

VBA - 如何超链接另一个工作表中的多个单元格

如何将特定工作表的excel保存到另一个Excel工作表python中

Excel-如何从另一个工作表中检索相应的值?

如何从excel中的另一个工作表中提取价值?

如何在不激活工作表的情况下使用VBA过滤另一个工作表中的范围

如何在QUERY函数中引用另一个工作表?

如何在SwiftUI中从工作表视图转到另一个页面?

如何在特定工作表中运行宏,但根据从另一个 Excel 文件/工作表维护的值控制启动?

VLOOKUP从另一个工作表中获取数据

如何在另一个Excel实例中连接到OPEN工作簿

Excel VBA宏:在一个工作表中查找/匹配单元格到另一个工作表中的列

如何将一个表中的数据替换为另一个表中的数据,类似于Excel中的vlookup?