1
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

I am not able to put table array value under Vlookup in VBA to point to another excel sheet.

How do I do that?

2
  • Is the other workbook open? Commented Sep 24, 2018 at 17:46
  • Yes the other workbook is open Commented Sep 24, 2018 at 18:24

1 Answer 1

4

First, when working with Vlookup you need to handle errors, such as when Vlookup was unable to find a match, you can use If Not IsError(Application.VLookup(.... to achieve this.

Second, in your case you don't need to use On Error GoTo errorbox:, just use the Vlookup error handling I wrote in the first point.

Third, you can use If Trim(ActiveCell.Value2) <> "" Then to verify there is a valid text or number inside ActiveCell rather than empty spaces.

Fourth, you should avoid using ActiveCell, and use fully qualified object instead.

Last, you want to make sure "Fruit Code.xlsx" workbook is open before using the Vlookup, as suggested by @Tim Williams in the comments above.

Modified Code

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.