Unable to get worksheet the VLookup property of the WorksheetFunction Class error - vba

Private Sub TextBox2_AfterUpdate() 'Badge Number
On Error GoTo Err
Dim tbl As ListObject, fndStr As String
Set tbl = Sheet9.ListObjects("EmployeeList")
fndStr = Trim(Me.TextBox2.Value)
MsgBox fndStr
If fndStr <> "" Then
Me.TextBox3.Value = Application.WorksheetFunction.VLookup(fndStr, tbl, 2, False) '<-- Error Line
End If
Exit Sub
Err:
MsgBox Err.Description
End Sub
I have a table named as "EmployeeList" and I am doing simple vlookup using Badge number but I am getting the error for unknown reason. I know there are similar questions asked before but I did read before posting this.
As you can clearly see the table name in the image and Entered value that is 10 for the first parameter on vlookup function but it doesn't returns any value but gives error. Don't know what's wrong.
'I tried this as well
Me.TextBox3.Value = Application.WorksheetFunction.VLookup(fndStr, Sheet9.Range("A1:F" & Rows.Count), 2, False) '<-- Error Line
'And this
Me.TextBox3.Value = Application.WorksheetFunction.VLookup(fndStr, Sheet9.Range("EmployeeList"), 2, False) '<-- Error Line
Also for unknown reason I can't do
Application.Vlookup as well
Like when I do Application.V
Vlookup doesn't shows up in the list.

There are two issues.
The first, you have tried to solve, is that you need a Range as Arg2in Vlookup. Since your tbl is a ListObject. you could simply use tbl.Range, see ListObject.Range Property.
The second is, that Vlookup will not find strings in a column of numbers. And your first column is a column of numbers. So you need to convert the string into number.
Me.TextBox3.Value = Application.WorksheetFunction.VLookup(CDbl(fndStr), tbl.Range, 2, False)
should work.

Please find the code below, i have used evaluate method to get vlookup result.
Private Sub TextBox2_AfterUpdate()
Dim fndStr As String
On Error GoTo Err_Desc
fndStr = Trim(Me.TextBox2.Value)
MsgBox fndStr
If fndStr <> "" Then
'// Using Eval method
Me.TextBox3.Value = Evaluate("=VLOOKUP(" & fndStr & ",EmployeeList[#All],2,0)")
End If
Exit Sub
Err_Desc:
MsgBox Err.Description
End Sub

Related

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
I am not able to put table array value under Vlookup in VBA to point to another excel sheet.
How do I do that?
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

Application.WorksheetFunction.Search and .IsNumber don't work in VBA: type mismatch error; fixing match function character limit

I'm trying to work around the MATCH's function's character limit using this answer:
=MATCH(TRUE,INDEX(ISNUMBER(SEARCH(A2,Dict!A:A)),0),0))
I tried the full version:
Sub test
Dim KEY_CONTRACT_ROW As Variant
KEY_CONTRACT_ROW = _
Application.WorksheetFunction.Match(True, _
Application.WorksheetFunction.Index(Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("testing string", _
ThisWorkbook.Worksheets("Sheet1").Range("A:A"))), 0), 0)
End Sub
It didn't work - Type mismatch error.
So I tried the shorter version:
Sub test
MsgBox (Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("testing string", _
ThisWorkbook.Worksheets("Sheet1").Range("A:A"))))
End Sub
To the same result. At the same time when I use this formula manually on worksheet it works fine.
WorksheetFunction produces a breaking error when an error occurs. Instead, use the Match method of the Application object. Actually, you can avoid WorksheetFunction altogether.
Sub test()
Dim KEY_CONTRACT_ROW As Variant
Dim rngSearchRange As Range
'Define the search range as to avoid a whole column reference
With ThisWorkbook.Worksheets("Sheet1")
Set rngSearchRange = Application.Intersect(.UsedRange, .Range("A:A"))
End With
'Search for the specified search string
With Application
KEY_CONTRACT_ROW = .Match(True, .IsNumber(.Search("testing string", rngSearchRange)), 0)
End With
'Check whether a match was found
If IsError(KEY_CONTRACT_ROW) Then
MsgBox "Match not found!", vbExclamation
Else
MsgBox "Match found!", vbExclamation
End If
End Sub

Subtract two ranges and clear the contents from result

I'm trying to subtract RangeA - RangeA+offset to get a new range. After this i need to clear all the values within it. My problem is that the variable columnrange is empty and i'm unable to realize what i'm doing wrong.
Dim rng1 As String
Dim rangeA As Range
Dim columnrange As Range
Dim clearrange As Range
rng1 = TextBoxA.Value
If Not IsNull(RangeboxA.Value) Then
On Error Resume Next
Set rangeA = Sheets("Plan1").Range(RangeboxA.Value)
rangeA.Select
Selection.Copy
rangeA.Offset(0, rng1).Select
ActiveSheet.Paste
columnrange = rangeA.Resize(rangeA.Rows.Count, rangeA.Columns.Count + rng1).Value
columnrange.Select
On Error Resume Next
If rangeA Is Nothing Then MsgBox "Verificar informação A"
End If
This code moves a user-defined range by a user-defined amount.
Sub RemoveRangeOverlap()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Plan1")
Dim rngOffset As Integer
Dim rangeA As Range, rangeB As Range
Dim cellRange() As String
On Error GoTo ErrHandle
rngOffset = CInt(TextBoxA.Value)
If RangeBoxA.Value <> "" Then
Set rangeA = ws.Range(RangeBoxA.Value) 'Set old range
cellRange = Split(CStr(RangeBoxA.Value), ":") 'Set start/ending cells
ReDim Preserve cellRange(LBound(cellRange) To UBound(cellRange))
Set rangeB = ws.Range(ws.Range(cellRange(0)).Offset(0, rngOffset), _
ws.Range(cellRange(1)).Offset(0, rngOffset)) 'set new range
rangeA.Copy rangeB 'copy new range
Application.CutCopyMode = xlCopy 'remove marching ants
If rangeA.Columns.Count <= rngOffset Then 'remove old values
rangeA.Clear
Else: ws.Range(ws.Range(cellRange(0)), _
ws.Range(cellRange(1)).Offset(0, rngOffset - rangeA.Columns.Count)).Clear
End If
Else: MsgBox "Missing target range input.", vbCritical, "Insufficient Data"
End If
ErrHandle:
If Err.Number = 438 Then
MsgBox "Invalid range format in range input box." & vbNewLine & _
"Proper range format example: A1:A1", vbCritical, "Error 438"
ElseIf Err.Number = 13 Then
MsgBox "Only numbers may be input as the range offset amount", _
vbCritical, "Error 13: Type Mis-match"
ElseIf Err.Number = 5 Then Exit Sub
Else: Err.Raise Err.Number
End If
End Sub
How the code works:
The first thing we have set up is information control from user-defined values. To accomplish this (which can also be done with If Then statements to prevent the errors from ever occurring in the first place) I've included an error handling line at the end. We know what 3 errors we expect to get depending on what the user provides us with.
Error 438 will occur if the user tries to set RangeBoxA's value as a non-range value.
Error 13 will occur if the user tries to input anything that isn't a number as the offset value.
Error 5 will occur because I'm bad at error handling and I'm not sure why it's occuring.. It loops my error statement at the end after whichever error is thrown (being a non-vba error).
Next we split up the range supplied by the user into two 'cells'. Using this we can apply some simple math to show where the copy destination will be as well as delete the proper amount of old range values.
If the number of columns is greater than the user supplied offset, then the new and old ranges will overlap. Some simple math will remove the old cells while preserving the new one's
If the number of columns is less than the user supplied offset, delete all of the old cells because they won't be overlapping.
Let me know if this works for you.

VBA Match function to find ActiveCell Value on inactive sheet and change value on active sheet

I try to find the value of the Active cell where my cursor is using the application.match function on a different sheet. If it is found i want to change the value of a cell on my active sheet based on the ActiveCell.Row and a determined column.
I tried to use this code
Sub test()
Dim wert As String
Dim such1 As String
Dim var As Integer
such1 = ActiveCell.Value
On Error Resume Next
var = Application.Match(such1, Worksheets(Test1).Columns(1), 0)
If Err = 0 Then
wert = Sheets("Test2").Cell(var, "N").Value
Sheets("Test2").Cell(ActiveCell.Row, "O").Value = wert
Else
MsgBox "Value not existent"
End If
End Sub
Somehow i always get the error message. I dont understand why though. Do you have any idea?
Use syntax like this:
Option Explicit
Public Sub test()
Dim foundRow As Variant
Dim activeRow As Long
Dim foundN As String
activeRow = ActiveCell.Row
foundRow = Application.Match(ActiveCell, Worksheets("Test1").Columns(1), 0)
If Not IsError(foundRow) Then
foundN = Worksheets("Test2").Cells(foundRow, "N").Value
Worksheets("Test2").Cells(activeRow, "O").Value = foundN
Else
MsgBox "Value not existent"
End If
End Sub
Mistakes in your code:
Worksheets(test1) should be Worksheets("Test1")
Worksheets("Test2").Cell should be Worksheets("Test2").Cells ("s" at the end of Cells)
There are subtle differences between Application.Match() and WorksheetFunction.Match()
WorksheetFunction.Match() is not as reliable as Application.Match()
WorksheetFunction.Match() throws a run-time error
you need to use the statement On Error Resume Next to bypass the VBA error
Application.Match() returns an Error Object
the statement On Error Resume Next doesn't work
to check the return value you have to use If IsError(Application.Match(...))
Note how foundRow is defined: Dim foundRow AsVariant
The return value can be the row number (a Long) or an Error object (Variant)

Getting a "Subscript out of range" error, and I don't know whats wrong. (I'm kind of new to vba)

This is my code:
Private Sub New_User_Create_Click()
CreateUsername_L = LCase(Create_User_Text.Text)
For Each ws In Worksheets
If (Worksheets(CreateUsername_L).Name <> "") Then
MsgBox "Username is already taken! Try again!"
Create_User_Text.Text = ""
NewUser.Hide
Exit For
Else
Dim work As Worksheet
With ThisWorkbook
Set worksheetname = .Sheets.Add(After:=Worksheets(Worksheets.Count))
worksheetname.Name = CreateUsername_L
On Error Resume Next
Create_User_Text.Text = ""
NewUser.Hide
[B1].Value = (UserName + "'s Personal Profile")
Exit For
End With
End If
Next ws
End Sub
If you could help me with this it would be much appreciated
(also the error only occurs when the condition is not met e.g there is no sheet with the same name as "CreateUsername_L". When the condition is met the message box with "Username is already taken..." shows up so its only when the condition is not met when this error occurs)
You can't test for the existance of the worksheet name like you're trying to do. The 'Subscript out of range' error is looking for that worksheet name and if it can't find it then you get your error. You can write a function to test for the existence of a name and use that instead. Here's mine:
Public Function doesSheetNameExist(inputName As String) As Boolean
Dim ws As Worksheet
On Error GoTo ErrorCatch
Set ws = Thisworkbook.Worksheets(inputName)
'if no error here then worksheet exists
doesSheetNameExist= True
CloseFunction:
Exit Function
ErrorCatch:
doesSheetNameExist= False
Resume CloseFunction
End Function
This handles the error within the function. Alternatively you could loop through each worksheet and test the name.
You'd then replace your line
If (Worksheets(CreateUsername_L).Name <> "") Then
with
If doesSheetNameExist(CreateUsername_L) Then