Writing Ranges into formulas with VBA - excel

I am using variable ranges, and want to insert those ranges into a formula that can be saved in a document that does not use VBA.
Do I have to use a with statement?
My If Statement works until I try and insert a relative range. I searched and didn't see much on this, so this issue is probably so simply I am an idiot.
The program will be doing things all over the worksheet, so relative coding is needed. The number of items in the range changes with each iteration. I will be using an end range integer [myRange] for the number instead of 10, but I wanted to simplify what I am struggling with into the smallest steps.
Dim Test As String
Test = "=IF(COUNTIF(" & ActiveCell.Offset(1, 0).Address & ":" & ActiveCell.Offset(10, 0).Address & "" _
& ")," & """Not Complete""" & "," & "" & """"")"
ActiveCell.Formula = Test
Desired output in target cell:
"=IF(COUNTIF($J$3:$J$12),"Not Complete","")"

As mentioned in comments, your COUNTIF statement is currently invalid. What are you counting in the range J3:J12? This needs to be added (in place of "CRITERIA" in below solution) before your equation will be valid
Test = "=IF(COUNTIF(" _
& ActiveCell.Offset(1).Resize(10).Address(True, True) _
& ",""CRITERIA""), ""Not Complete"", """")"
If you want your output to actually have the quotes you can output
Chr(34) & Test & Chr(34) which seems cleaner than wrapping the whole string in quotes from a readability point of view IMO

Related

Inserting semicolon between two quotation marks in VBA

I am trying to insert a formula automatically within a certain range but somehow I am getting a runtime error 1004. Can someone please assist ?:
The Original in excel:
=#IF(ISNA(MATCH($B6;StepList;0));"";IF(#INDEX(StepIdTable;MATCH($B6;StepList;0);COLUMN())="";"";INDEX(StepIdTable;MATCH($B6;StepList;0);COLUMN())))
My Code:
Dim sMyString As String
sMyString = Chr(34) & Chr(34) & Chr(59) & Chr(34) & Chr(34)
.Range("C6:C25").Formula = "=#IF(ISNA(MATCH($B6,StepList,0)),"""",IF(#INDEX(StepIdTable,MATCH($B6,StepList,0),COLUMN())=" & sMyString & ",INDEX(StepIdTable,MATCH($B6,StepList,0),COLUMN())))"
The problem is "";"". I have tried everything to make this work
Does anyone have an idea ?
Not sure if this is the answer because I'm in a different locale and can't test it directly, but if all your other delimiters are commas, shouldn't the one in sMyString be as well?
sMyString = Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34)
where 44 is the code for a comma.
On the other hand, if they are all supposed to be semicolons, then the formula should have been
Range("C6:C25").Formula = "=#IF(ISNA(MATCH($B6;StepList;0));"""";IF(#INDEX(StepIdTable;MATCH($B6;StepList;0);COLUMN())=" & sMyString & ";INDEX(StepIdTable;MATCH($B6;StepList;0);COLUMN())))"
But when using Formula, you have to enter the formula string using commas as delimiters regardless of locale. However in your case, if you want to standardise on semicolons both in VBA and on your sheet, you could try FormulaLocal:
Range("C6:C25").FormulaLocal = "=#IF(ISNA(MATCH($B6;StepList;0));"""";IF(#INDEX(StepIdTable;MATCH($B6;StepList;0);COLUMN())=" & sMyString & ";INDEX(StepIdTable;MATCH($B6;StepList;0);COLUMN())))"
see this reference
BTW I find it helpful to put the whole formula string into a debug.print statement to see how it looks.
It's all about the number of double quotes. Try one of this approaches:
Sub test1()
sMyString = """"""";"""""""
frm = "=IF(F13=" & sMyString & ",1,0)" 'so
frm = "=IF(F13="""""";"""""",1,0)" 'or so
Debug.Print frm '=IF(F13=""";""",1,0) within the cell
Range("F13").Formula = frm
End Sub
Explanation: since the escape of double quotes is their doubling, each conversion of a string containing double quotes adds or subtracts (depending on the direction of the conversion) these pairs, resembling a cascading effect

Need macro to write the formula in a cell not the answer (ouput)

I cannot figure this out - I either get a Named? error or Application defined error on trying everything.
Dim sAmt As Integer
Dim sOriginalAmount As Integer
sOriginalAmount = ActiveCell.Value
sAmt = Application.InputBox("How much additional cost?", Type:=2)
ActiveCell.Formula = sOriginalAmount + sAmt
What I want Excel to do is write the formula in the cell not the output.
For example - Currently if I have sOriginalAmount as 15 and I enter sAmt as 20, on running the code, it gives the answer 35 in the cell, but I want it to write =sum(valueofsOriginalAmount + valueofsAmt) so that at a later time I can see what was the original amount and how much was added.
Can anyone please help? I have tried & "" in various combinations but I just can't get it. Apologies for such a noobie question, but I am self learned and I code for my work only.
This should work.
ActiveCell.Formula = "=" & sOriginalAmount & "+" & sAmt
Or if you actually want to use SUM.
ActiveCell.Formula = "=SUM(" & sOriginalAmount & "," & sAmt & ")"

Translate Excel array formula to VBA

I am making a calendar with different events.
For that I have the following formula to lookup multiple hits with multiple conditions:
=IFERROR(INDEX(Returnarray, SMALL(IF(Value1 & Value2=Lookuparray1&Lookuparray2, ROW(Returnarray)-MIN(ROW(Returnarray))+1,""), ROW()-Offset)),""))
I would like to translate this formula to a VBA function, but I can't get it to work.
I tried with Evaluate and with appication.worksheetfunction but no success.
Function MultipleLookup(Offset As Integer, ReturnArray As Range, Value1 As Range, Lookuparray1, Value2 As Range, Lookuparray2 As Range)
MultipleLookup = Evaluate("=IFERROR(INDEX(Returnarray, SMALL(IF(Value1 & Value2=Lookuparray1&Lookuparray2, ROW(Returnarray)-MIN(ROW(Returnarray))+1,""), ROW()-Offset)),""))")
End Function
I also tried to change the formula and use match instead of if but then it only gives me the first match.
Can somebody please help me to make it work?
Would it be possible to have a function with a variable amount of criteria?
Thank you
Your Evaluate function is one entire string right now and it doesn't use the variables. Try something like this:
MultipleLookup = Evaluate("=IFERROR(INDEX(" & Returnarray.Address & ", SMALL(IF(" & Value1.Address & " & " & Value2.Address & "=" & Lookuparray1.Address & "&" & Lookuparray2.Address & ", ROW(" & Returnarray.Address & ")-MIN(ROW(" & Returnarray.Address & "))+1,""), ROW()-" & Offset & ")),""))")

Application-defined or object-defined error when using .formula

I've been struggling to get a formula typed into a cell on a sheet. it's my activesheet (definitely).
Source is a file with full path. the sheet name is ... and lta_col_letter is the column letter I'm typing the formula into.
ActiveSheet.Range(lta_col_letter & 2).Formula = "=IFERROR(INDEX('[" & Source & "]...'!$G:$G,MATCH(" & versionref_col_letter & "2,'[" & Source & "]...'!$B:$B,0))," & Chr(34) & Chr(34) & ")"
I'm not sure why I'm getting this error. Help please!
EDIT:
Works when I added the missing [ brackets, but when it goes into the cell it adds the file name again after the sheet name and before the cell reference.It looks fine in a msgbox.
Looks like you are missing some opening square brackets around source.
ActiveSheet.Range(lta_col_letter & 2).Formula = "=IFERROR(INDEX('[" & source & "]...'!$G:$G,MATCH(" & versionref_col_letter & "2,'[" & source & "]...'!$B:$B,0)), text(,))"
To examine these types of errors, put a ' before the opening = and run the procedure to put the formula into the cell as a string. Go to the worksheet and perform a visual examination and try to remove the '. Make corrections until you have a working formula then transfer the corrections to the VBA formula string.
Since it seems that you have used an open workbook to retrieve the workbook name into source, you might consider using the Range.Address Property with External:=True to retrieve a fully punctuated external address.
dim sourceG as string, sourceB as string
sourceG = workbooks(source).worksheets("...").range("G:G").address(external:=true)
sourceB = workbooks(source).worksheets("...").range("B:B").address(external:=true)
ActiveSheet.Range(lta_col_letter & 2).Formula = _
"=IFERROR(INDEX(" & sourceG & ", MATCH(" & versionref_col_letter & "2, " & sourceB
& ",0)), text(,))"

Excel VBA: inserting WHEN formula into specific range of cells with variable changing column

Hello dear StackOverflow users,
My issue is regarding inserting a Formular via Macro into specific range of cells. Again, again and again.
So the Basic function of the formula should be the following:
=WHEN('ZEK '!F3="X";"6";WHEN('ZEK '!G3="X";"8";"1"))
In my macro it has to Change the column for the next specific range.
This is Happening in a for Loop for i growing.
meaning --> =When('ZEK '!$F$"& i+2 &".......
or in any other Syntax that should work. My try fairly does not, thats why I need your help.
This is my Initial try where i exchanged literally everything with strings:
Sub 123()
Dim a,b,c As String
a = 1
b = 6
c = 8
....
'used and declared variables k, x, f, a, b, c
Range(Cells(k + 2, 5), Cells(k + 27, 5)).FormulaR1C1 = _
"=WHEN('ZEK'!$F$" & f & "=" & x & ";" & a & ";WHEN('ZEK'!$G$" & f & "=" & x & ";" & b & ";" & c & "))"
End Sub
With that i get Runtime Error 1004. (changed it to .Formula from .FormulaR1C1)
I hope i gave enough Information, so that you could help me.
This really does not have to be performant, i just Need to get the formula into about 100.000 cells with i changing for each Range of cells
I think it's a language problem... Try
"=IF('ZEK'!$F$" & f & "=" & x & "," & a & ",IF('ZEK'!$G$" & f & "=" & x & "," & b & "," & c & "))"
Notice the use of IF and , as a delimiter instead of ;. Is WHEN even a valid worksheet function? To be honest I don't know if the worksheet functions get translated or not when setting the formula via VBA. The delimiters are adapted though.
edit: there is also the .FormulaLocal property that should work with ; as delimiter! So change .Formula to .FormulaLocal. This will probably cause an error if you execute it on a machine that uses , as default delimiter so I'd try to stick with .Formula.

Resources