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"")"
Related
This is the part I currently have:
Worksheets("Data").Cells(3, CRup).FormulaR1C1 = "=VLOOKUP(RC[-7],'[" & TOD & "]" & flt & "'!R1C1:C18, " & CRupT & ",0)"
Try this vba function Application.WorksheetFunction.VLookup
Example :
Dim lk_Val = 'Lookup Value String'
Worksheet("DestinationSheet").Range("A1") = WorkApplication.WorksheetFunction.VLookup(lk_Val,Workbooks("YourSourceWorkbook").Sheets("YourSourceSheet").Range("A:B"),2,False)
As far as i know the workbook must be opened
I'm experiencing the following issue:
Sheets("Workbook 1 ").Range("N" & integerv).Formula = "=Workbook2!""" & column_string & """ 3)"
(integerv being some integer) keeps returning " Object-defined or application-defined error".
column_string is a string variable obtained by
column_string = Split(Cells(a,b).Address(True,False), "$")(0)
essentially just containing the column letter of the cell I want to reference.
Am I passing the string variable incorrectly ? And what would my code have to look like if I wanted to additionally pass an integer variable instead of "3" ?
Any help appreciated, I've been stuck with this for a fair while now.
Just a Thought or Two About Formulas in VBA
How would you write your formula for column A in Excel?
=Workbook2!A3
In VBA you would do this:
rng.formula = "=Workbook2!A3"
You can aslo write it like this:
rng.Formula = "=Work" & "book2" & "!A3"
or like this:
rng.Formula = "=" & "Work" & "book" & "2" & "!" & "A3"
But of course in this case (your post) you wanna write it like this:
rng.Formula = "=Workbook2!" & "A" & "3"
Now when you make it dynamic, you know what to do:
rng.Formula = "=Workbook2!" & column_string & "3"
As FunThomas mentioned in the comments you can use a variable (and you should especially when there is a more complicated one). Then you could create a new Sub just for the formula and write...
Dim strFormula As String
strFormula = "=Workbook2!" & "A" & "3"
...and in the Immediate window (CTRL+G) see the written result with...
Debug.Print strFormula
...and modify the formula until you get it right.
You my try the formula in this way:
Dim b As Long, column_string As String
b = 2: column_string = "C" 'the result simulation of your extraction using Split
Sheets("Workbook 1 ").Range("N" & integerv).Formula = "=Workbook2!" & column_string & 3
'having the b variable value, no need to extract the column letter:
Sheets("Workbook 1 ").Range("N" & integerv).Formula = "=Workbook2!" & cells(3, b).Address(0, 0)
I searched on internet, without any help coming out of that...
I simply would like to be able to have my VBA code to write this formula in a cell :
=IF(C4="-"; "-"; Cars!C4*C4*Data!$C$8)
As you guessed, there is a page called "Cars" and one called "Data" where I pick the informations needed.
Of course, as it is a VBA code, the C4 will be 2 variables, one for the C and one for the 4 that will evolve...
Actually, I tried this :
Worksheets("Calculation").Range(Column & PosStartCalc + 1).Formula = "=" & "IF(" & Column & PosStartCalc & " = " & "" - "" & ";" & " - " & ";" & "Cars!" & Column & PosStart & "*" & Column & PosStartCalc & "*" & "Data!" & "C" & "8" & ")"
(The variable Column contains the column letter and the variable PosStartCalc contains the row number)
This hurts my eyes and apparently VBA's ones too as it gives the error "Run-Time error '13': Type Mismatch'
Could anyone tell me how to do that?
Thanks in advance !
Try the following, assuming the column variable is a string and row a long variable. I might not have all the variables right, but you'll be able to get what I meant to do here.
Sub test()
Dim Col As String: Col = "C"
Dim Rw As Long: Rw = 4
With ThisWorkbook.Sheets("Calculation")
Debug.Print "=IF(" & Col & Rw & "=""-"",""-"",Cars!" & Col & Rw & "*" & Col & Rw & "*Data!$C$8)"
.Cells(Rw + 1, Col).Formula = "=IF(" & Col & Rw & "=""-"",""-"",Cars!" & Col & Rw & "*" & Col & Rw & "*Data!$C$8)"
End With
End Sub
So what you might forget easily is to use the , as parameter delimiter in a VBA programmed formula. When you put this on your sheet Excel will automatically replace that with the appropriate delimiter for your region.
Another thing to keep in mind; whenever you about to use a string value in such an function, don't forget to wrap it in double quotes!
Don't forget to remove the Debug.print .... line. It was merely there to show the output :)
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.
VBA Insert function VLOOKUP into range,lookup range in other workbook. The file containing the lookup table is achieved using filename_AcctMgr = Application.GetOpenFilename(, , "Select Acct Mgr File", "Select"), then opening the file. Let's call this workbook2.
In workbook1 I am adding the VLOOKUP formula into "F2" and looking up Column "A" values in workbook2, columns A:C. I Then copy the formula to all rows of column "F".
I cannot find the syntax required to properly reference the workbook2 range in columns A:C.
ActiveCell.Formula = _
"=VLOOKUP(activecell.offset(0,-5).address,'ws.name'!A:C,3,FALSE)"
Can anyone suggest the proper syntax?
Try this:
Range("F2").Resize(10).Formula = "=VLOOKUP(A2,[Book2]Sheet1!$A:$C,3,FALSE)"
Or
Range("F2:F10").Formula = "=VLOOKUP(A2,[Book2]Sheet1!$A:$C,3,FALSE)"
EDIT: Sorry I forgot the piece about the filename as a variable:
Dim MyFile As String
Dim vSplit As Variant
Dim iCnt As Integer
MyFile = Application.GetOpenFilename(, , "Select Acct Mgr File", "Select")
vSplit = Split(MyFile, "\")
iCnt = UBound(vSplit)
vSplit(iCnt) = "[" & vSplit(iCnt) & "]"
MyFile = Join(vSplit, "\")
Range("F2:F10").Formula = "=VLOOKUP(A2,'" & MyFile & "Sheet1'!$A:$C,3,FALSE)"
You will need to add error handling in case someone clicks cancel. Also I doubt you want to add the formula to all rows in column f so just define the range you want. My examples is rows 2 to 10.
I am assuming you want the name of the sheet / range to be in a variable, rather than hard-coded. As it it, you have the name of the variable in the middle of your string, but it will be treated as a string, not a variable containing a string.
I suggest that you do something like the following:
Dim sheetName, lookupFrom, myRange ' always declare your variables
sheetName = "This is the sheet name" ' note I added some spaces to make it challenging
lookupFrom = ActiveCell.Offset(0, -5).address
myRange = "'" & sheetName & "'!A:C" ' putting quotes around the string so it's always valid
ActiveCell.Formula = "=VLOOKUP(" & lookupFrom & "," & myRange & ", 3, FALSE)"
You can of course do this all at once - it just gets messy to look at:
ActiveCell.Formula = "=VLOOKUP(" & ActiveCell.Offset(0, -5).Address & ", '" & sheetName & "'!A:C, 3, TRUE)"
Further note - the sheetName can of course contain the name of the other workbook - but you need name of workbook AND sheet... so
sheetName = "[Book2]Sheet1"
would be fine.
In your example you used ws.name (without proper quoting) - but that would not have given you the full path since you need both the workbook and the worksheet name to make sure you reference the right data. Better be explicit - if Excel can make the wrong assumptions about what you want, it will - and you will be left scratching your head...
Since you actually showed you had opened the book, you have the name of the file (the workbook) in your variable filename_AcctMgr. Then you should be able to use:
sheetName = "[" & filename_acctMgr & "]Sheet1"
and take it from there.