VBA Code for Vlookup - vba

When I reference a specific cell in vlookup VBA code like below I can get the code to return the correct answer.
Application.VLookup(Sheets("Setup").Cells(2, 1),
Sheets("Download").Range("A:G"), 7, 0)
However, if I replace the code with a variable (VLDate) then I get an error
Application.VLookup(VLDate, Sheets("Download").Range("A:G"), 7, 0)
I've tried to make Dim VLDate As String but this didn't work too.
Any suggestions?

In your example Sheets("Setup").Cells(2,1) is not a string.
Cells returns a Range.
Dim VLDate As Range
Set VLDate = Sheet("Setup").Cells(2,1)
If your first example worked, using the above code to set the value of VLDate should make your second example work too.
Edit
Might have misunderstood your question a little so while the above is true it might not help!
Could you provide an example value for VLDate, and also the cell formatting type and an example value from the range that its looked up in?

I think I know what the problem is. The vlookup's first input has to be of the same data type of what you're looking for. For example if in the cells you are searching you have only numbers, then try dimensioning VLDate as a number, if you try to dim it as string it won't find a match and will give you the type mismatch error.
You can dim VLDate as variant, which is easier, but do not use quotes if you're looking for a number.
try adding, for debugging purposes, the line
MsgBox(CStr(Application.VLookup(Sheets("Setup").Cells(2, 1), Sheets("Download").Range("A:G"), 7, 0))
and if you het a msgbox with Error 2042 it menas it couldn't find a match, therefore you should be using the wrong data type.
The only situation that you use string is if the destination cells contain something like ="21" in their formulas, because then it is a string.
hope it helps

Related

VBA: Using Array Formula

I want to find a row number based on two criteria, in column C and E. My data looks like this:
I have googled my problem and using the Match function as an array formula works for this (worked when I used it in Excel, not VBA), but I can't figure out how to make it an array formula in VBA. Different solutions, be it using "[]" or .Evaluate didn't work for me (maybe that was my mistake, though). So how would I modify this code to get the result I want:
Sub Test1()
Dim rowDB As Long
Dim wsDB As Worksheet
Set wsDB = ActiveSheet
rowDB = WorksheetFunction.Match(CDate("30.06.2020") & "EX0500-0001", wsDB.Range("C7:C366") & wsDB.Range("E7:E366"))
End Sub
The error I get is "error 13: type mismatch", so I'm not sure if there's another issue here or just the lack of an array formula.
I played with this for a bit and found several problems:
It seems that CDate() doesn't like "30.06.2020" as input and gets a type error. It seems to be happy with "30-06-2020" so maybe use that format instead or just search for string "30.06.2020" instead? This should be ok as long as all of the date formats are consistent.
The WorksheetFunction.Match() second parameter must be a contiguous range and yours is not. Also I don't think the expression wsDB.Range("C7:C366") & wsDB.Range("E7:E366") makes sense; if you want to combine ranges use the Union() function. But this will not work here because as mentioned the range is not contigous.
I don't think it is possible to use WorksheetFunction.Match() to search for multiple values, so you might have to search for the date in coulmn C and the string in column E separately.
Here is some vba I got working for just searching for one value:
Sub Test4()
Dim rowDB As Long
Dim wsDB As Worksheet
Set wsDB = ActiveSheet
rowDB = WorksheetFunction.Match("30.06.2020", wsDB.Range("C7:C366"))
Debug.Print rowDB
End Sub
Also, If a match is not found, it will get a "Application-defined or object-defined error" so you will need to implement some error handling.

VBA Offset Match Not Working

I am trying to run a goal seek setting a certain cell equal to zero by changing another cell in Excel with VBA.
The cell I want to set to zero changes location so I need to use a match offset combination I think.
I get a compile error Invalid qualifier when I run the code though. Any ideas?
Thank you.
Private Sub CommandButton1_Click()
Dim x As Integer
x = Application.WorksheetFunction.match("G3", Range("I6:SF6"), 0).Value
Range("I199").Offset(0, x.Value).GoalSeek Goal:=0, ChangingCell:=Range("GN197")
End Sub
Try replacing:
"G3"
with:
Range("G3")
Try using named range instead of using Range reference. This way even if rows or columns are added you named range is still available.
As per official documentation, the return value of WorksheetFunction.Match is a Double. So you probably do not have Value available. Try removing it.
PS: I do not have a system with Excel to test this.
PS2: You did not indicate the line producing the error.

VBA Match Function "Method 'Match' of Object 'WorksheetFunction' Failed"

I'm trying to use the Match VBA function in a programming project in Excel to get the first row number with a "1" in it. The code I'm using is:
Dim BorradorVar As Integer
BorradorVar = WorksheetFunction.Match(1, Sheets("Usuarios").Range("A1,A100"), 0)
Can someone explain what I'm doing wrong? Thanks!
You should refer to Range as
Range("A1:A100")
instead of
Range("A1,A100")
Using comma you refer to A1 and A100 only.
Also, if you are not sure if there is a match or not, you can use Application.Match and store the result in a Variant variable instead. The difference is that Application.Match returns an error when it fails, and then you can check if it has failed or not.
Example (check MSDN for full code):
Dim var As Variant
var = Application.Match(Cells(iRow, 1).Value, Worksheets(iSheet).Columns(1), 0)
If Not IsError(var) Then
Debug.Print "There is actually a match"
Else
Debug.Print "No match found"
End IF
A word of warning: If you match after row 32,767 your code will not run, because it exceeds the range of Integer. I suggest using Long instead of Integer. Using Long is better practice in VBA anyway.
Finally, note that if someone changes the name of the worksheet, this code will not run. It is safer to refer to the worksheet by using its sheet ID instead of its name (Disclaimer: I have written the accepted response to that question).

Trouble with undefined Object in VBA Run-Time error '91'

I've been working all week to prepare a VBA application, which I'll be using in a meeting today. Unfortunately the code that has been running all week last week without a hitch, has decided to break over the weekend.
I constantly get Object variable or With block variable not set Run-time error '91' from this statement:
With Sheet5
Set adjrng = .Range(.Cells(.Range("G43:G60").Find(.Range("H39").Value).Row, 10), .Cells(.Range("G43:G60").Find(.Range("H39").Value).Row, 21))
End With
idea is to set a range in the row of the Range G43:G60 where the Value of H39 matches from Column 10 to Column 21.
Anybody spot the issue? My brainz are to nervous and sleepy this morning...
Thanks a bunch
Ben
EDIT:
After playing a bit with find and replace, the issue seems to be that excel has not yet properly calculated the "lookin" and "lookup" Ranges G43:G60 and H39. A simple recalculation didn't make excel rediscover the contents but when I used one of my input toggles to display a different value in those cells, and the went back to the original it did manage to find it.
Maybe using find for this is bad style, the find formula has these kind of hicups usually or any other comments on this? For now everything works fine again, but I'm afraid of running into these issues again. Any tips would thus still be appreciated.
EDIT: (from comment below)
We have a dynamic range (G43:J60) where unique identifiers are listed in column G and data is to the right. if something is changed in the data part of the range AND the lines uniqued identifier in column G matches the one in cell H39 a sub() is triggered via worksheet_ change intersect(target, adjrng) Defining that adjrng is the part that throws errors when find returns null.
I believe you are simply trying to set a range hoping that there will be two matches to the value in H39 within the G43:G60 range. While I avoid on Error Resume Next (never could adjust to the logic of breaking something in the hope to accomplish something), I always check that the values will be there when I look for them.
Dim rwUNIQ as long
Set adjrng = nothing
With Sheet5
if cbool(application.countif(.Range("G43:G60"), .Range("H39").Value)) then
rwUNIQ = application.match(.Range("H39").Value, .Range("G43:G60"), 0)
Set adjrng = .Cells(42 + rwUNIQ, 10).resize(1, 11)
end if
if not adjrng is nothing then
'do something with adjrng
end if
Set adjrng = nothing
End With
That checks to make sure that there are at least two H39 values in G43:G60 before proceeding. There is no further error control because we've counted at least two of them. You might want to compensate with an Else for when there isn't. If a single H39 value was found, you also might want to select a single row.
Remember that the .Find uses many parameters that were retained from the last time Find was used, whether in VBA or with a user on the worksheet. You have a real lack of parameters that specify the options that Find should use to proceed. e.g. xlPart or xlWhole, After:=what?, look in formulas or values, etc.
EDIT:* Modified the code to look for a single instance of the value in H39 and .Resize to expand the width (as per OP's comments).

Getting a value from a named range in VBA

I want to retrieve a value from named range. Imagine a named range that has X columns and Y rows. I want to return a value, e.g., from column 2, row 3. The issue I experience is that if I write the code and run it, Excel throws an error. If I write the code into the watch window, it returns fine. See below
...
Dim NamedRange As Variant: NamedRange = Range(NamedRangeName)
...
Dim ReturnValue As Object
Set ReturnValue = NamedRange(RowIndex, ColumnToRetrieveIndex) 'Throws Run-time error 424. Object required
If I write
NamedRange(RowIndex, ColumnToRetrieveIndex)
into the watch window, I can see the correct value of the cell.
I don't know VB much so I guess it's just some kind of syntax error how I want to pass it into the ReturnValue but I just can't figure it out.
Use this
ThisWorkbook.Names("myNamedRange").RefersToRange(1,1)
To get the value from the first cell in the named range "myNamedRange"
With ThisWorkbook.Names you can access all named ranges of all the sheets within the current workbook.
With RefersToRange you get a reference to the actual range.
This looks like a good place to put a handy note (as it's a top search result):
If you name a cell "TopLeft", then Sheets(1).Range("TopLeft").Value gets the contents, and Sheets(1).Range("TopLeft").Offset(2,3).Value gets the value from 2 down, 3 across from there.