how to use variable containing strings in formula vba - vba

I ask the user input for a string and then need to incorporate this into a formula. I searched on other questions but didn’t get the desired output.
Sname = InputBox("Enter name")
Cells(2, 32).FormulaR1C1 = _
=CONCATENATE(J2,""-"",K2,""-"",L2,""-"" "" & Sname & "" -"",T2,U2,V2,W2,X2,Y2,""-"",AB2,""-"",AC2)
suppose i enter AAA
i want the formula on cell(2,32) to be
=CONCATENATE(J2,"-",K2,"-",L2,"-" & "AAA" & "-",T2,U2,V2,W2,X2,Y2,"-",AB2,"-",AC2)

Try this:
Cells(2,32).Formula = _
"=CONCATENATE(J2,""-"",K2,""-"",L2,""-"" & """ & Sname & """ & ""-"",T2,U2,V2,W2,X2,Y2,""-"",AB2,""-"",AC2)"
There was a slight mixup with your quotation marks around the variable.
This one works for me.

swap " for ' Tip: you can use CTRL+U
=CONCATENATE(J2,'-',K2,'-',L2,'-' & 'AAA' & '-',T2,U2,V2,W2,X2,Y2,'-',AB2,'-',AC2)
Add a replace function
Replace("=CONCATENATE(J2,'-',K2,'-',L2,'-' & 'AAA' & '-',T2,U2,V2,W2,X2,Y2,'-',AB2,'-',AC2)","'", Chr(34))
Chr(34) equal to caracter "

Related

Excel VBA - insert formula in a set of rows with variable reference directly or replacing a string for example "\=" with "="

I have the goal to write a formula in a set of rows. Some references in the formula have to change each row.
I implemented the following script:
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 0 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."";A" & i & ";IF(Q" & i & "=""Ist"";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=""Lz."";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=""Ist+Lz.-Bedarf"";OFFSET(A" & i & ";-3;0);)))))"
Let temprng = "M" & i
Range(temprng).Select
ActiveCell.Value = "\=" & formcolM
next i
With this script I am writing a string each row in my excel table at column M.
I noticed that if the formula hasn't the symbol "\" , you can find an error .
In order to avoid the error I thought to leave the symbol "\" and to use a trick deleting it after (because I don't know how to solve with R1C1 formula. I read some answers on Stackoverflow, but unfortunately I did not understand )
The replacing script after the for cycle:
Columns("M:M").Replace What:="\=", Replacement:="=", LookAt:=xlPart
The strange thing is that the macro doesn't delete it.
Infact when the script finishes , it seems that nothing happened, without errors. But if I want substitute "\=" with another symbol, for example "*", the replacing script works.
I did not understand if the problem is :
the replace method did not recognized the symbol "=" to search
I cannot use the replace method because the symbol "=" disturbs in some way , I don't know in what.
OR, is there another simplest way to get this task done?
Someone could help me in order to fix? I should have the formula working in the column M , automatically with vba (not with another formula in the excel sheet) .
Thanks in advance for your time.
We can apply the formula directly. The issue is that vba is very US-EN Centric and all formula when using the .Formula needs to be in that format.
Also since your formula refers to values in a row 3 above the one in which it is put we need to start the loop at 4 not 0. There is no row 0
There are two ways, in US-En format with English functions and , as the deliminator using .Formula:
Dim i As Integer
For i = 4 To 100
Range("M" & i).Formula = "=NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."",A" & i & ",IF(Q" & i & "=""Ist"",OFFSET(A" & i & ",-1,0),IF(Q" & i & "=""Lz."",OFFSET(A" & i & ",-2,0),IF(Q" & i & "=""Ist+Lz.-Bedarf"",OFFSET(A" & i & ",-3,0),)))))"
Next i
Or using .FormulaLocal and the formula as you would write it in your native tongue.
Dim i As Integer
For i = 4 To 100
Range("M" & i).FormulaLocal = "=NUMERO.VALORE(SE(Q" & i & "=""Bedarf kum."";A" & i & ";SE(Q" & i & "=""Ist"";SCARTO(A" & i & ";-1;0);SE(Q" & i & "=""Lz."";SCARTO(A" & i & ";-2;0);SE(Q" & i & "=""Ist+Lz.-Bedarf"";SCARTO(A" & i & ";-3;0);)))))"
Next i
By the time I got this worked out, Scott already had an answer. I just wanted to post your original code modified to work. I would suggest his method.
Sub TestScript()
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 4 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=" & "Bedarf kum." & ";A" & i & ";IF(Q" & i & "=" & "Ist" & ";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=" & "Lz." & ";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=" & "Ist+Lz.-Bedarf" & ";OFFSET(A" & i & ";-3;0);)))))"
temprng = "M" & i
Sheets("Sheet1").Range(temprng).Select
ActiveCell.Value = " = " & formcolM
Next i
End Sub

How can I get the value of a combobox into a string in vba module?

I have a form that example exports do xml based on query. That query is build with the conditions of combobox.
The combobox have only one field.
What I want is to, in vba module, name de xml file with the conditions of the combobox.
Example: value of combobox: 03, Lucas, Roger, 23.
file: myXML.Save "C:\teste\03_Lucas_Roger_23.xml"
You can use this expression:
FileName = "C:\teste\" & Replace(Replace(Me!YourCombobox.Value, ",", "_"), " ", "") & "xml"
file: myXML.Save FileName
You can concatenate the values like this.
I've added an additional test for null, because if no value is selected on one or more of the ComboBoxes it will throw an error.
If IsNull(ComboBox1.Value) Or IsNull(ComboBox2.Value) Or IsNull(ComboBox3.Value) Or IsNull(ComboBox4.Value) Then
MsgBox ("Not all values selected!")
Else
Dim myFileName As String
myFileName = "C:\teste\" & ComboBox1.Value & "_" & ComboBox2.Value & "_" & ComboBox3.Value & "_" & ComboBox4.Value & ".xml"
myXML.Save myFileName
End If

Excel custom hyperlink for each cell in range using VBA

I have a module that removes all formulas from an entire sheet and then, it should, create a hyperlink formula on each cell using the cell value.
Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Test")
ws1.Range("B33:F533").Value = ws1.Range("B33:F533").Value
For Each i In ws1.Range("B33:B533")
i.Formula = "=HYPERLINK(""https://somelocation/" & i.Value & """,""" & i.Value & """)"
Next
End Sub
EDIT: It's now working perfectly. Thanks For all the help!
i.Formula = "=HYPERLINK('https://somelocation/"&i.Value&","& i.Value"')"
Has an error in the formula. At the i.Value"') you are missing &, i.Value & "'. The correct one, that 'compiles', is added below:
i.Formula = "=HYPERLINK('https://somelocation/" & i.Value & "," & i.Value & "')"
Also it is worth noting that instead of writing "&i.Value&" and let the VBA IDE add the spaces, it is better to do it yourself, eg: " & i.Value & ".
You're code has 2 flaws, you should add the last & to get a syntax correct formula, and add spaces between the " and &, or else VBA won't see it is right.
Edit; a third flaw:
The line to create the formula is wrong too. Let's break it down:
"=HYPERLINK('https://somelocation/" & i.Value & "," & i.Value & "')"
The parameter in the formula would be:
'https://somelocation/" & i.Value & "," & i.Value & "' so an output example of this line could be 'https://somelocation/1,1'. At first, I thought you are writing an URL with a comma, alright..? But then I looked at the HYPERLINK function in Excel and it requires two parameters. You are only giving one parameter. Excel formulas also expect a double quote instead of a single quote. You can escape a double quote in VBA like this "".
The correct line should be:
i.Cells(1, 1).Formula = "=HYPERLINK(""https://somelocation/" & i.Value & """,""" & i.Value & """)"

Write text to log file Columns

How do I write to the columns in a .log file?
I.e there are columns for "Log Text","Component","Date/Time"
How do I specify these when writing to a file?
I've got half of it working:
dim str As String ="<![LOG[" & message & "]LOG]!><time=""" & Now.ToLongTimeString & """" & " date=""" & Now.ToShortDateString & """ component=""" & component.ToString & """" & " type=""1""" & " Thread=""" & t & """" & ">"
File.AppendAllText(logfile, str & vbCrLf)
But the component, date / time and thread values arent displaying properly.
What am I missing ?
*edited
The file path is "C:\Programdata\server.log"
So some of the text is getting into it in the right place, just not all of it.
So the log text column will get populated with "message" and thread comes in with the number but the date/time and component are empty.
I'd attach a pic but i dont have enough rep :/
In a sentance, Im trying to replicate this:
http://www.jetico.com/web_help/bcwipe6_enterprise/img/log_viewer.jpg
but not all of my columns are displaying data.
Try dividing your data into columns using commas as suggested by #Blackwood, but use string.format as you seem to have lots of extra "" in there
Dim str As String = String.Format("![LOG[{0}]LOG]!,time={1}, <date= {2}, component= {3}, type=1, Thread={4}", Message, Now.ToLongTimeString, Now.ToLongDateString, component.ToString, t)
File.AppendAllText(logfile, Str() & vbCrLf)
I'm not sure what you are doing with the <> tags.
Solved.
This is to do with the format of the data I was trying to write.
Time has to be in the format
Now.ToLongTimeString & "." & Now.Millisecond & "-60"
and date has to be seperated with - instead of /
Dunno why - when viewed the time doesnt go to that length and the date is displayed with "/"
The viewer im using for the log was cmtrace.
This was the line that got it working was ..
<![LOG[" & message & "]LOG]!><time=""" & Now.ToLongTimeString & "." & Now.Millisecond & "-60" & """" & " date=""" & d & """ component=""" & component.ToString & """" & " type=""1" & """ Thread=""" & t &""">

Excel Error:1004 - Trying to write cell formula

I'll try to make this as short as possible.
I need to rewrite the formulas of a number of cells depending on what worksheet they're located in.
Dim sFrmla As String
Dim rSomerange As Range
Let sFrmla = "=OFFSET(INDIRECT(INDIRECT(" & Chr(34) & "E" & Chr(34) & "&ROW()));0;"
Let rSomerange.Formula = sFrmla & wsSheet.Name & "_ZERO_SCALE)"
Let rSomerange.Formula = sFrmla & wsSheet.Name & "_FULL_SCALE)"
Let rSomerange.Formula = sFrmla & wsSheet.Name & "_PRCSUNIT)"
This crashes at the second line (Zero_scale) and gives me a runtime error 1004. I have already made sure that the range itself exists and is writable.
Funny part is that the same code but without the formula string works just fine.
Let rSomerange.Formula = wsSheet.Name & "_ZERO_SCALE)"
Any ideas?
there is no need to use Let keyword. It's odd in this case.
no matter what is the default separator for your regional
settings (comma , or semicolon ;), you should always use comma
, with Range.Formula. If you'd like to use your regional
separator (semicolon ; in your case), use Range.FormulaLocal
instead.
So, you should use:
sFrmla = "=OFFSET(INDIRECT(INDIRECT(" & Chr(34) & "E" & Chr(34) & "&ROW())),0,"
rSomerange.Formula = sFrmla & wsSheet.Name & "_ZERO_SCALE)"
or
sFrmla = "=OFFSET(INDIRECT(INDIRECT(" & Chr(34) & "E" & Chr(34) & "&ROW()));0;"
rSomerange.FormulaLocal = sFrmla & wsSheet.Name & "_ZERO_SCALE)"
or shorter version:
sFrmla = "=OFFSET(INDIRECT(INDIRECT(""E""&ROW())),0,"