Excel VBA INDEX MATCH (not pasting a formula using the code) - excel

I've seen several questions asked around using INDEX MATCH on multiple criteria within VBA, but they all seem to revolve around pasting a formula into a cell.
I'm looping thru a ListObject and trying to do a lookup on 3 criteria on a diff sheet, but I want the value pasted into the cell not the formula. I've tried using various combos of Application.Index, Application.WorksheetFunction.Index, Application.Match, Application.WorksheetFunction.Match and Evaluate() but I'm still getting #Value! (when I don't get a an Error). Some of what I've tried below (it's prob a very simple mistake I'm making).
wsSrc has the following ranges as part of a ListObject and I want to paste the result onto wsDest.
rngDate = Range("Table24[date]") 'Date
rngFrom = Range("Table24[from]") 'String
rngTo = Range("Table24[to]") 'String
rngLookup = Range("Table24[lookup]") 'Double
Based on a combination of a Date, From and To I want to lookup a value in rngLookup.
I've tried:
Application.Index(rngLookup.Address, _
Application.Match(strDate & "USD" & strTo, _
rngDate.Address & rngFrom.Address & rngTo.Address))
I've also tried:
x = wsSrc.Evaluate("INDEX(" & rngLookup.Address & _
",MATCH(" & strDate & "USD" & strTo & "," & _
rngDate.Address & "&" & rngFrom.Address & "&" & rngTo.Address)
I've even tried converting the date using CStr(CDate()) which works on in Excel, but not in the VBA.
No joy on either, any thoughts? Again, to confirm I want just the value not the formula pasted into a cell.

This worked for me using a table and columns of the same name:
Dim sht As Worksheet, dt, sFrom, sTo
Set sht = ActiveSheet ' e.g.
dt = DateSerial(2017, 12, 18)
sFrom = "B"
sTo = "C"
Debug.Print sht.Evaluate( _
"INDEX(Table24[lookup],MATCH(1," & _
"(Table24[date]=" & (dt * 1) & ")*" & _
"(Table24[from]=""" & sFrom & """)*" & _
"(Table24[to]=""" & sTo & """),0))")
Assumes your table's dates are actual dates and not strings.

Related

how to update just entered formulas to get data from closed excel file?

I'm working on a macro that needs to load data from multiple excel files. For that i wrote a function that enters formulas to get the information from the closed Excel files. The formulas will be copied and paste values so i don't have pages full formulas linked to other files. My problem is i have two Excel files that are loading data from a Cube+ Data Bank in a pivot table. This formulas need at first longer to pull the data and when i do the paste values i only get "Bezug" (German error for value not found). This is the function:
Public Function GetDataClosedWB(SourcePath As String, _
SourceFile As String, _
sourceSheet As String, _
sourceRange As String, _
targetRange As Range, _
Optional blFormula As Boolean = False) As Boolean
Dim strQuelle As String
Dim Zeilen As Long
Dim Spalten As Byte
'On Error GoTo InvalidInput
strQuelle = "'" & SourcePath & "[" & SourceFile & "]" & _
sourceSheet & "'!" & _
Range(sourceRange).Cells(1, 1).Address(0, 0)
Zeilen = Range(sourceRange).Rows.Count
Spalten = Range(sourceRange).Columns.Count
With targetRange.Cells(1, 1).Resize(Zeilen, Spalten)
.Formula = "=IF(" & strQuelle & "="""",""""," & strQuelle & ")" '<-- this is where the formula is been entered
If Not blFormula Then .Value = .Value '<-- this is where the formula is been pasted
End With
GetDataClosedWB = True
Exit Function
InvalidInput:
MsgBox "Die Quelldatei oder der Quellbereich ist ungültig!", _
vbExclamation, "Get data from closed Workbook"
GetDataClosedWB = False
End Function
I tried entering:
a time brake
a message
forcing formula calculation
copy paste later in macro
nothing worked.
funny thing: if i play the macro step by step, the formulas will get the data before i get to the end.

Excel VBA Error 1004 in cell formula replacement

Note : I'm French, so normally I use french functions (e.g. SI for IF or SOMME for SUM) and the default decimals separator is the coma and not the point (e.g. 1,03 for 1.03)
I have to replace many formulas in an Excel workbook, and all of them have the same template, but I could not use the fast fill-in tool, so I'm trying to make a macro for this.
First, here is how the cell currently looks :
='C:\...\[file1.xlsx]'sheeta!$XXa$nna - 'C:\...\[file2.xlsx]'sheetb!$XXb$nnb
So basicely, I want to keep these two addresses (I will name them ad1 and ad2) to make the followig formulas :
=IF(AND(ISNUMBER(VALUE(ad1;"."));ISNUMBER(VALUE(ad2;".")));SUM(VALUE(ad1,".");PRODUCT(-1;VALUE(ad2;".")));"NA")
Which substracts two numbers stored with differents formats, and displays NA if at least one of them is not a number.
Here is the macro I wrote :
Sub tmp()
Dim c As Range
Dim adr1 As String
Dim adr2 As String
Dim frm As String
For Each c In Application.Selection.Cells
adr1 = Split(Split(c.Formula, "=")(1), "-'")(0)
adr2 = "'" & Split(Split(c.Formula, "=")(1), "-'")(1)
frm = "=IF(AND(ISNUMBER(VALUE(" & adr1 & ";"".""));ISNUMBER(VALUE(" & adr2 & ";""."")));SUM(VALUE(" & adr1 & ";""."");PRODUCT(-1;VALUE(" & adr2 & ";""."")));""NA"")"
c.Formula = frm
Next
End Sub
The error occures on the last action c.Formula = frm.
I've already checked frm's value, and it is good.
I think there is a synthax error on my formula, but I couldn't find it. Can someone help me ?
Thanks in advance !
VBA accept only US format formula. US format use , instead ;
frm = "=IF(AND(ISNUMBER(VALUE(" & adr1 & ",""."")),ISNUMBER(VALUE(" & adr2 & ","".""))),SUM(VALUE(" & adr1 & ","".""),PRODUCT(-1,VALUE(" & adr2 & ","".""))),""NA"")"

vba Sumif with variables and R1C1

I'm trying to run the below code and it gives me
Run-Time Error "1004"
Application-defined or Object-defined error
Every Single Time!!
Attached is a snippet of the code, any suggestions what's wrong? (The numbers in the Range(Cells( * ) sections are actually mostly variables in my overall macro, it's pretty complex but I've taken them out for simplicity here)
Code:
'Declare variables
Dim CriteriaRng As String
Dim SumRng As String
Dim Criteria As String
'Set a variable for each of the 3 parts of the SUMIF Formula
CriteriaRng = "'" & Sheets(1).Name & "'!" & Range(Cells(2, 4), Cells(88, 4)).Address
SumRng = "'" & Sheets(1).Name & "'!" & Range(Cells(2, 3), Cells(88, 3)).Address
Criteria = Chr(34) & "=" & Chr(34) & " & RC[-1]"
'Here goes the SUMIF Formula
With Sheets(2).Range(Cells(4, 13), Cells(9, 13))
Debug.Print "So the Whole Formula Should be:" & Chr(13) & "= SUMIF(" & CriteriaRng & ", " & Criteria & ", " & SumRng & ")"
'That was a vain attempt to find out what was wrong with the formula; didn't work though.
.FormulaR1C1 = "= SUMIF(" & CriteriaRng & ", " & Criteria & "," & SumRng & ")"
'Then adds NumberFormat and stuff here, but that isn't relevant to this question.
End With
The error always hits on the line where it's putting in the .FormulaR1C1 = .
Yes, I know I could get the same result using a nested loop, but that would return just the value without the SUMIF formula - I need that formula so the sheet updates when edited (without needing a macro - I'm sending the sheet on to other people who won't have or want any macros, but might need to edit the data).
Can anyone point out to me what is wrong? I'm prepared for it to be something pretty basic - only last week I spent 2 hours figuring out a problem from misspelling 'Columns' !!!
Any and all advice welcome - Many Thanks in advance.

Translate a worksheet formula in VBA

Can somebody help me to write this formula in excel VBA?
=IF(ISERROR(VLOOKUP(A3,Temp!$A$3:$A$595,1,FALSE)),A3,"0")
My code is getting stuck with :"syntax error"
Sub checkDuplitems()
Application.ScreenUpdating = False
Const top As Integer = 3
Dim bottom As Long
bottom = Sheets("Temp").Cells(Rows.Count, top).End(xlUp).row
With ThisWorkbook.Sheets("trash").Range("A" & top & ":A" & bottom)
.Formula = "=IF(ISERROR(VLOOKUP(A" & top & ",Temp!$B$" & top & ":$B$" & bottom & _
",1,FALSE)),A" & top & ", & '" 0" & ," '")"
.Value = .Value
.SortSpecial
End With
'Call something...
End Sub
You have a concatenation problem in the second line of the .Formula line.
To emulate the formula you have at the top of your question (which is wrong incidentally because you should be pointing to $B$3:$B$595 or something like that because your look up cell A3 should not be inside the VLOOKUP range).
Try this new .Formula line:-
.Formula = "=IF(ISERROR(VLOOKUP(A" & top & ",Temp!$B$" & top & ":$B$" & bottom & _
",1,FALSE)),A" & top & ", " & "0)"
Are you sure you want to use top as both the starting row in column A and the column to get the bottom row from the Temp worksheet? The important column on the Temp worksheet is column B (i.e. 2) not C (i.e. 3).
If you are putting formula(s) into Trash!A3:A595 that reference Trash!A3:A595 then these are circular references and cannot be resolved under normal conditions. I'll put the formulas into column Z.
If you are operating with Excel 2007 or newer then I would humbly propose this alternate that uses the worksheet's IFERROR function and does not attempt to make text out of the 0 returned value.
Const top As Integer = 3
Dim bottom As Long
bottom = Sheets("Temp").Cells(Rows.Count, "B").End(xlUp).Row '<~~change here
With ThisWorkbook.Sheets("trash")
With .Range("Z" & top, .Cells(Rows.Count, "A").End(xlUp).Offset(0, 25))
.Formula = "=IFERROR(VLOOKUP(A" & top & ", Temp!$B$" & top & ":$B$" & bottom & _
", 1, FALSE), 0)" '<~~ big change here
.Value = .Value
End With
End With
It is also curious as to why the number of rows of formulas in the Trash worksheet must be governed by the number of rows of data in the Temp worksheet. I would have thought that the number of values in column A of the Trash sheet should govern how many formulas go into the Trash worksheet.

Concatenating SumIfs in VBA

I'm trying to get this segment of code to execute. This is a simplified version of the code. I've included the relevant code. I'm trying to concatenate strings and named ranges into a SumIfs formula, but I get error 1004 "Application-defined or Object-defined error." I have a working line of code above this problem section that is similar with the exception of doing a sum function, instead of sumif. Any idea how to get this code to execute? Thank you.
Dim wb As Workbook
Dim ara As Worksheet
Dim inv As Worksheet
Dim ARBlock As Range
Dim Invoices As Range
Dim AgedDays As Range
Set wb = ThisWorkbook
Set ara = wb.Sheets("AR Aging")
Set inv = wb.Sheets("Invoices")
Set ARBlock = ara.Range("a6")
Set Invoices = inv.Range("a6", inv.Range("a6").End(xlDown))
Set AgedDays = Invoices.Offset(0, 6)
'Populate A/R age buckets
For i = 6 To ARBlock.Rows.Count + 6
With ARBlock(i - 5, 1).Offset(0, 3)
.Value = "=SumIfs(" & Invoices.Offset(0, 4).Address & "," & _
Invoices.Address & "," & ARBlock(i - 5, 1).Value & "," & _
Invoices.Offset(0, 6).Address & ","" <= "" & &O30)"
End With
Next i
End Sub
The line beginning with ".value" is where I'm getting the error message. P.S.: I need the cell to contain the concatenated formula, as opposed to the output value.
UPDATE 1:
As some suggested I updated the .value line to:
.Offset(0, 3).Formula = "=SumIfs(Invoices.Offset(0, 4).Address,Invoices.Address,ARBlock.cells(i - 5, 1).Value)"
I'm still getting the same error. Some auditing I've done:
Removing the "=" before "Sumifs" allows the code to run fine; pasting in the formula into the target cell as text. In this form, my output for i=1 goes to ARBlock.cells(1,1), as it should.
I also used Debug.Print to view all of the components of the formula:
Debug.Print ARBlock.Cells(i - 5, 1).Address
'output $A$6
Debug.Print ARBlock.Cells(i - 5, 1).Value
' output International Business Machines
Debug.Print Invoices.Offset(0, 4).Address
'output $E$6:$E$255
Debug.Print Invoices.Address
'output $A$6:$A$255
I suspected the issue might be that the range dimensions might have been off, but this is not the case. My next suspicion is that the output International Business Machines needs to be in " " for the formula to read it correctly. I hardcoded in
""International Business Machines""
to see if this would fix the formula, but I keep getting the same error once I add the "=" back in. The formula syntax is correct, the dimensions are the same between the sum range and criteria range. Anyone else have any ideas?
.Offset(0, 3).Formula = "=SumIfs(Invoices.Offset(0, 4).Address,Invoices.Address,ARBlock.cells(i - 5, 1).Value)"
Change to:
.Offset(0, 3).Formula = "=SumIfs(" & Invoices.Offset(0, 4).Address & ", " & Invoices.Address & ", " & chr(34) & ARBlock.Cells(i - 5, 1).Value & chr(34) & ")"
EDIT: Added quotes chr(34) around your string!
Your ARBlock(i - 5, 1).Value most likely is an empty cell, which messes the SUMIFS formula as it builds it with to consecutive commas

Resources