Application-defined or object-defined error with formula VBA - vba

I'm new to VBA and encounter the
application-defined or object-defined error
while doing it.
Set twb = ThisWorkbook
Set extwbk = Workbooks.Open("abc.xlsx")
Set x = extwbk.Worksheets("FILTERED").Range("$A:$A")
With twb.Sheets("FILTERED")
For rw = 9 To .Cells(Rows.Count, 1).End(xlUp).Row
.Cells(rw, 34).Formula = "=IF(ISERROR(VLOOKUP(.Cells(rw, 1).Value2, x, 1, False))=TRUE,""New"",""Old"")"
Next rw
End With
This can be done manually but I'm asked to do it by programming. It is simply apply the formula from AH9 to the end of the data. May I know is there any coding error in the for loop?
Thanks in advance.

Dont put VBA variables inside your string formula. Resolve them in VBA and inject the result into the formula:
.Formula = "=IF(ISERROR(VLOOKUP(" & .Cells(rw, 1).Value2 & "," & _
x.Address(External:=True) & ", 1, False))=TRUE,""New"",""Old"")"
p.s. dont use =TRUE to check for a boolean, things like If ISERROR(Something) = TRUE don't make sense. Just If ISERROR(Something).
.Formula = "=IF(ISERROR(VLOOKUP(" & .Cells(rw, 1).Value2 & "," & _
x.Address(External:=True) & ", 1, False)),""New"",""Old"")"
If you want the formula to be dynamic and recalculate accordingly when the cell at (rw, 1) changes in the future, use .Address instead of .Value2:
' vvvvvvvv
.Formula = "=IF(ISERROR(VLOOKUP(" & .Cells(rw, 1).Address & "," & _
x.Address(External:=True) & ", 1, False)),""New"",""Old"")"

Related

Concatenate two ranges without looping

I want to concatenate two ranges into one WIHTOUT using a loop.
Below is the code. The lines with comment's is basically the solution I want to avoid.
With ws_AUoM
lCountEntriesInAUoMFile = .Cells(Rows.Count, "B").End(xlUp).Row
.Range("O2:O" & lCountEntriesInAUoMFile).Value = .Range("B2:B" & lCountEntriesInAUoMFile).Value & .Range("F2:F" & lCountEntriesInAUoMFile).Value
' For lLoopCounterAUoM = 2 To lCountEntriesInAUoMFile
'
' .Cells(lLoopCounterAUoM, "O").Value = .Cells(lLoopCounterAUoM, "B").Value & .Cells(lLoopCounterAUoM, "F").Value
'
' Next lLoopCounterAUoM
End With
This line:
.Range("O2:O" & lCountEntriesInAUoMFile).Value = .Range("B2:B" & lCountEntriesInAUoMFile).Value & .Range("F2:F" & lCountEntriesInAUoMFile).Value
returns the error "Type Mismatch". I have double checked the sizes and location of each range. Yet it does not work. What am I missing here?
You can do this:
Dim r As Long
With ws_AUoM
r = .Cells(.Rows.Count, "B").End(xlUp).Row
.Range("O2:O" & r).Value = .Evaluate("B2:B" & r & " & F2:F" & r)
End With
Evaluate knows you're giving it an array formula, and will return the resulting array, which you can assign directly to the sheet.

VBA Run-time Error 1004 for Special Characters in Soft-coded Vlookup Function

When I was trying to throw a vertical bar "|" into my vlookup function, I got a 1004 error. I am not sure where it came from.
Initially the data table looks like this:
And my code was like this:
Sheets("Sheet 1").Cells(i, 2).Formula = "=VLOOKUP($A" & i & ",Data!$A$1:$B$" & LastRow & "," & ColmNum & ",0)"
Everything worked fine till the format of the data table got changed to:
So I had to throw the vertical bar "|" into my code. My new code was like this:
NewKey = Sheets("Sheet 1").Cells(i, 1).Value & "|" & Sheets("Data").Cells(i, 2).Value
Sheets("Sheet 1").Cells(i, 3).Formula = "=VLOOKUP(" & NewKey & ",Data!$A$1:$B$" & LastRow & "," & ColmNum & ",0)"
Apparently Excel 2010 did not like my codes and threw me a 1004 error. I am wondering if anyone knows a solution to this. Thank you in advance for your help.
NewKey needs to be in quotes when the formula is placed on the sheet, so you need to include the quotes in the string:
NewKey = Sheets("Sheet1").Cells(i, 1).Value & "|" & Sheets("Sheet1").Cells(i, 2).Value
Sheets("Sheet1").Cells(i, 3).Formula = "=VLOOKUP(""" & NewKey & """,Data!$A$1:$B$" & LastRow & "," & ColmNum & ",0)"

Run-time Error Using Formula From Workbook Variable

I am using Vlookup formula from another workbook in my code. The other workbook named as a variable TifuliWB Workbook but I keep getting an error run time error 1004. I am sure that it's such a small mistake of mine that stops the sub but I can't know what.
With MainWB.Worksheets(2)
LR = .Cells(Rows.Count, "A").End(xlUp).Row
.Range("J2:J" & LR).FormulaR1C1 = _
"=VLOOKUP(RC[-8]," '"[" & TifuliWB.Worksheets(1) & "]"'"!C1:C71,65,FALSE)"
.Range("J2:J" & LR).NumberFormat = "m/d/yyyy"
.Cells.Copy
End With
Try referencing the columns' full external address instead of concatenating in the workbook and worksheet name.
.Range("J2:J" & LR).FormulaR1C1 = _
"=VLOOKUP(RC[-8]," & TifuliWB.Worksheets(1).range("A:BS").address(1, 1, external:=true, referencestyle:=xlr1c1) & ",65,FALSE)"
'alternately in xlA1 style
.Range("J2:J" & LR).Formula = _
"=VLOOKUP(J2," & TifuliWB.Worksheets(1).range("A:BS").address(1, 1, external:=true) & ",65,FALSE)"
Your original should have used the .Name or .FullName property and there were some string concatenation issues.
.Range("J2:J" & LR).FormulaR1C1 = _
"=VLOOKUP(RC[-8], '[" & TifuliWB.fullname & "]" & TifuliWB.Worksheets(1).name & "'!C1:C71,65,FALSE)"

Deploy VBA Cell Reference in Array Formula

So I'm trying to do a couple things with this subroutine but can't get VBA to execute the .FormulaArray function.
Create a named range using offset & lastrow function
Use cell references to insert into the array formula
--
Sub namedrange()
Dim firstrow As Long
Dim LastRow As Long
Dim ColToLetter, absolute, Title, mc, mc1
ActiveCell.Offset(0, -1).Select
absolute = ActiveCell.Address
LastRow = ActiveSheet.Cells(Rows.Count, ActiveCell.Column).End(xlUp).Row
firstrow = ActiveCell.Row
ColLetter = Mid(ActiveCell.Address, 2, 1)
ActiveSheet.Range(ColLetter & firstrow & ":" & ColLetter & LastRow).Name = Range(ColLetter & "1").Value
Title = Range(ColLetter & "1").Value
ActiveCell.Offset(0, 1).Select
mc = ActiveCell.Offset(-1, 0).Address
mc = Mid(mc, 2, 3)
mc1 = Replace(mc, "$", "")
ActiveCell.FormulaArray= "=IF(ROWS(mc & "":"" & mc1)>SUM(IF(FREQUENCY(IF(Title<>"""",MATCH(Title,Title,0)),ROW(Title)-ROW(absolute)+1),1)),"""",INDEX(Title,SMALL(IF(FREQUENCY(IF(Title<>"""",MATCH(Title,Title,0)),ROW(Title)-ROW(absolute)+1),ROW(Title)-ROW(absolute)+1),ROWS(mc & "":"" & mc1))))"
End Sub
The formula bar shows what the vba function is outputting, which is not what I want. I don't know why it won't output the references I've created like mc should be "$A$2" not "mc".
Also when I try to execute the FormulaArray code I get a runtime error 1004 "Unable to set the FormulaArray property of the Range class"
Your .FormulaArray content has some typos. Here's how it should look like (assuming all the above code is fine):
ActiveCell.FormulaArray= "=IF(ROWS(" & mc & ":" & mc1 & ")>SUM(IF(FREQUENCY(IF(Title<>" & chr(34) & chr(34) & ",MATCH(Title,Title,0)),ROW(Title)-ROW(absolute)+1),1))," & chr(34) & chr(34) & ",INDEX(Title,SMALL(IF(FREQUENCY(IF(Title<>" & chr(34) & chr(34) & ",MATCH(Title,Title,0)),ROW(Title)-ROW(absolute)+1),ROW(Title)-ROW(absolute)+1),ROWS(" & mc & ":" & mc1 & "))))"
In general, remember that if you want the value of a variable to be printed into a string, you cannot write "a=mc+3" but rather a = " & mc & "+3".

VBA show BOTH results and formula (for audit purposes) in the cell

I need help with my puzzle. I have written a code that works fine. Now a user wants to see not just the final result but also the formula written in VBA (for audit purposes) to verify that the results are OK. Is there a way to show BOTH results and formula in the same cell?
My code so far:
Sub Vlookup_Condition_VAT_table()
Dim Rng As Range
Dim i As Long
Application.ScreenUpdating = False
Workbooks("GST_recovery_overclaim.xlsm").Worksheets("MonthlyData_Raw").Activate
'Identify the Destination location to start populating vlookuped values
Range("AK2").Activate
With Worksheets("MonthlyData_Raw").Cells
Set Rng = .Range("A1:A" & .Cells(.Rows.Count, 1).End(xlUp).Row)
For i = 2 To Rng.Rows.Count
'populate the destination range with
'vlookup values from the list vlookup table
Rng.Cells(i, 37) = Application.VLookup(.Cells(i, 28), Sheets("VAT_apportionment_table_201310").Range("D:G"), 4, False)
Next
End With
Application.ScreenUpdating = True
End Sub
Thank you very much,
Russ
If you aren't looking at thousands of rows, you could try the following.
Instead of using this line to print the result of your vlookup formula:
Rng.Cells(i, 37) = Application.VLookup(.Cells(i, 28), Sheets("VAT_apportionment_table_201310").Range("D:G"), 4, False)
You could instead put the actual formula in the cell with this change
Rng.Cells(i, 37).Formula = "=VLOOKUP(" & _
.Cells(i, 28).Address & "," & _
"'" & Sheets("VAT_apportionment_table_201310").name & "'!D:G," & _
"4," & _
"False)"
--------------UPDATE BASED ON OP COMMENT-----------------------------
Adding error trapping via an ISERROR function (untested)
Dim errMsg as String
errMsg = "Not in exception list"
Rng.Cells(i, 37).Formula = "=ISERROR(VLOOKUP(" & _
.Cells(i, 28).Address & "," & _
"'" & Sheets("VAT_apportionment_table_201310").name & "'!D:G," & _
"4," & _
"False), " & errMsg & ")"
I created a variable for the error message for a couple of reasons.
Easier to debug later
Dealing with text in a formula that is being sent to the cell like this can be tricky. And using a variable gets around the trickiness.
Maybe add text to the result with the answer and the formula.
Rng.Cells(i, 37) = "Answer: " & Application.VLookup(.Cells(i, 28), Sheets("VAT_apportionment_table_201310").Range("D:G"), 4, False) & ", Formula: = Application.VLookup(.Cells(i, 28), Sheets("VAT_apportionment_table_201310").Range("D:G"), 4, False)"
If I undestood you correctly, you want to display the formula entered in a cell with the result. How about this?
'Assume that you have a Range("A1") equals to = cos(20)
Sub GetFormula()
Dim MyFormula As String
MyFormula = Replace(Range("A1").Formula, "=", "")
MsgBox ("Formula is : " & MyFormula _
& " Result is :" & Range("A1"))
End Sub