I am trying to create a formula using R1C1 format that will change based on a string containing a variable. I have tried creating the string and inputting it in the formula, as well as creating the string in the formula and none seems to work. Below is my code:
Dim NewXX As Integer
Dim NewXX1 As Integer
Dim CE As Integer
Dim PrevCE As Integer
Dim CEText As String
CE = Cells(NewXX - 1, 1).Value + 1
CEText = "=" & CE
ActiveCell.FormulaR1C1 = _
"=SUMIFS(R[-209]C8:R[1]C8,R[-209]C1:R[1]C1,CEText,R[-209]C2:R[1]C2,""<>Summary"")*(1+R1C16)"
CEText is the variable that will change every time the macro is run. A few things I have tried:
CEText
""CEText"",
'"&CEText&"',
"CEText",
""="""&CE&",
""=""CE,
All of these trials either give me an 'Expected: end of statement' error, or the formula displayed in the cells matches the text (not value) found in the code.
Any help would be greatly appreciated! I am fairly new to VBA and am always up for learning a better way to do things!
Thanks!
CEText is not need when you are equating and since CE is a number, we only need to worry about removing from formula string and concatenating:
ActiveCell.FormulaR1C1 = _
"=SUMIFS(R[-209]C8:R[1]C8,R[-209]C1:R[1]C1," & CE & ",R[-209]C2:R[1]C2,""<>Summary"")*(1+R1C16)"
If you want CEText then we do the extra quotes in the formula:
ActiveCell.FormulaR1C1 = _
"=SUMIFS(R[-209]C8:R[1]C8,R[-209]C1:R[1]C1,""" & CEText & """,R[-209]C2:R[1]C2,""<>Summary"")*(1+R1C16)"
The main issue is that any vba variable must be outside the quotes and concatenated with &
Related
I have a below formula which validates for IP address in Excel cell and works fine.
Dim cellAddress as Variant
cellAddress =Target.value 'Target is a Range
=AND(COUNT(FILTERXML("<t><s>"&SUBSTITUTE(A1,".","</s><s>")&"</s></t>","//s[.*1>-1][.*1<256]"))=4,LEN(A1)-LEN(SUBSTITUTE(A1,".",""))=3)
My problem is that I want to pass the cellAddress as a Dynamic value to my formula instead of 'A1'
Can somebody guide
You can create a Public Function that returns a Boolean, and pass in the cell reference as a Range to the function.
Here's an example of the code:
Option Explicit
' =AND(COUNT(FILTERXML("<t><s>"&SUBSTITUTE(A1,".","</s><s>")&"</s></t>","//s[.*1>-1][.*1<256]"))=4,LEN(A1)-LEN(SUBSTITUTE(A1,".",""))=3)
Public Function ValidateIPAddress(source As Range) As Boolean
' Get the first condition's value...
Dim xmltxt As String
xmltxt = "<t><s>" & Application.WorksheetFunction.Substitute(source.Value, ".", "</s><s>") & "</s></t>"
Dim sections As Variant
sections = Application.WorksheetFunction.FilterXML(xmltxt, "//s[.*1>-1][.*1<256]")
' Get the second condition's value...
Dim separators As Integer
separators = Len(Application.WorksheetFunction.Substitute(source.Value, ".", ""))
' Compare both conditions and return the result
ValidateIPAddress = Application.WorksheetFunction.Count(sections) = 4 And Len(source.Value) - separators = 3
End Function
And here's a snippet of the usage:
I tried to break out the formula you provided to make it legible without spending too much time on it. It can definitely be improved or you can even nest everything into one line if you wanted to, but I wouldn't recommend that because it'll be difficult to debug.
EDIT:
If you just wanted to replace the "A1" string you can concatenate the cellAddress variable with parts of the formula.
Here's a code snippet example:
Dim validationFormula As String
validationFormula = "=AND(COUNT(FILTERXML(""<t><s>""&SUBSTITUTE(" & _
Target.Value & ",""."",""</s><s>"")&""</s></t>"",""//s[.*1>-1][.*1<256]""))=4,LEN(" & _
Target.Value & ")-LEN(SUBSTITUTE(" & _
Target.Value & ",""."",""""))=3)"
Debug.Print validationFormula
Output of the formula when changing a cell's value to "A5":
Note: You have to replace all double quotes with 2 double quotes when handling quotes in strings.
I have a variable (set as string) that stores the value of a certain cell which is "1.0-123".
I then have to print a formula in a separate cell where I use this string inside of it. Something like:
Sub Test()
Dim n as string
n = Cells(1, 6).Value
Range("A1").Formula="=CONCATENATE(A2," & n & ",A3)"
End Sub
The issue here is that when my code prints this formula in excel, the value of the variable n becomes "1-123" instead of "1.0-123". Does anyone have any tips on how to fix this? Thanks in advance!
Text in a formula needs to be in quotes, so:
Range("A1").Formula="=CONCATENATE(A2,""" & n & """,A3)"
I want to convert a date in a cell to the date function so it is a formula. How do I get the date (using VBA), any date, say, 13 Jun 2020 to =DATE(2020, 6, 13) using variables for the year, month, and day. My code I have tried but won't work. The activecell shows 13-Jun-2020 as a date but appears in the function box as 13/06/2020
Sub ConvertDateToDateFunction()
Dim mvDay, mvMth, mvYr As Integer
mvDay = Left(ActiveCell, 2)
mvMth = Mid(ActiveCell, 4, 2)
mvYr = Right(ActiveCell, 4)
ActiveCell.Value = "=DATE(mvYr, mvMth, mvDay)"
End Sub
You have two problems. Here is the solution to the smaller one. The code below would do what you intend. It would convert a text string in the ActiveCell to a function of similar value and insert it in the cell below the ActiveCell.
Sub ConvertDateToDateFunction()
' if you don't say what it's supposed to be it'll be a Variant
Dim mvDay As String, mvMth As String, mvYr As String
mvDay = Left(ActiveCell.Value, 2)
mvMth = Mid(ActiveCell.Value, 4, 2)
mvYr = Right(ActiveCell.Value, 4)
ActiveCell.Offset(1).Formula = "=DATE(" & mvYr & "," & mvMth & "," & mvDay & ")"
End Sub
It's not entirely easy to insert a date as a text string in Excel because Excel will try to recognize a date for a date. Observe that any part of a string is a string, not an integer.
Now about your much bigger problem which is that you don't understand how Excel handles dates. It is such a big problem because you are trying to create a date in Excel in various ways and you run into all sorts of trouble. Read up on the subject here.
To give you a taste of what you will learn: what you see displayed in a cell isn't what the cell contains. There might be a formula in it and you see a number. And there might be a date and you see a string. What you see is determined by the cell's format. I think Chip Pearson's article will cover that topic. If you need to know more, look for "Cell formatting" on the web.
Your macro won't work because the date is a "real date" and not a string.
Try the following to convert the contents of cells containing a real date to a formula which will return the same date:
Option Explicit
Sub dtToFormula()
Dim R As Range, C As Range
Dim vDateParts(2)
Set R = [a1:a10]
'Set R = ActiveCell 'or Selection whatever range you want to convert
For Each C In R
If IsDate(C) And Not C.HasFormula Then
vDateParts(0) = Year(C.Value2)
vDateParts(1) = Month(C.Value2)
vDateParts(2) = Day(C.Value2)
C.Formula = "=DATE(" & Join(vDateParts, ",") & ")"
End If
Next C
End Sub
I have the following formula:
Range("ZZ1").Formula = "=SUMPRODUCT(--(A3:A" & LastRow & "<>""""))"
Now I wish I could use it directly to get the value without first putting it on my sheet.
Is there a way to get it inside a variable directly as below?
Dim x as long
x = "=SUMPRODUCT(--(A3:A" & LastRow & "<>""""))"
You can use Evaluate like this:
Dim x as long
x = Application.Evaluate("SUMPRODUCT(--(A3:A" & LastRow & "<>""""))")
This will evaluate in the context of the active sheet. You can also use the Worksheet.Evaluate method to evaluate in the context of a specific sheet.
One caveat: the formula string cannot be longer than 255 characters, but that does not appear to be an issue here.
You can use Application.CountIf:
x=Application.Countif(Range("A3:A" & LastRow),"<>"))
I need to convert a column of alpha-numeric values to strings in an Excel function. CStr(value) works fine, UNLESS the value is something like 123E4. In that case, Excel treats the value as 1230000 and returns the string "1230000". Using Format(value,"#") yields the same result. The result I want is the string "123E4".
How can I get this?
The input cells are downloaded from a web site. They use the "General" format. I pass the value in a cell to the following function.
Function Var2Str(varA1 As Variant, Optional strFmt As String = "#") As String
Dim strTry As String
Dim strMsg As String
Debug.Print varA1, VarType(varA1), TypeName(varA1)
strTry = CStr(varA1)
Select Case VarType(varA1)
Case vbDouble
strTry = Format(varA1, strFmt)
Case vbString
'no further action
Case Else
strMsg = "Unhandled VarType in Var2Str" _
& vbCrLf & vbTab & "vara1 = " & varA1 _
& vbCrLf & vbTab & "varType = " _
& VarType(varA1) & vbCrLf & vbTab _
& "TypeName = " & TypeName(varA1)
MsgBox strMsg, vbOKOnly, "Information"
End Select
Var2Str = strTry
Debug.Print Var2Str
End Function
You could try (1) getting what you see in a string, and (2) using that to set the value of the target cell.
Sub test_format2()
Dim r As Range, r1 As Range
Set r = Selection
For Each r1 In r
Dim n1 As String
n1 = r1.Text ' (1)
r1.Offset(0, 1).Formula = "'" & n1 ' (2)
Next r1
End Sub
This seems to be the only bullet proof option.
For instance, 1.2e8 seems to be a challenging case when varying column width.
Variations on this question are common here. An oz of prevention is worth a pound of cure. So best to prevent the problem instead of trying to cure it after the fact:
In order to prevent Excel from converting certain alpha-numeric data that look like numbers or dates, into numbers or dates, you must IMPORT rather than OPEN the file. When you do that, the Text-import-wizard will open and you can designate the column as text before excel does the conversion.
Exactly how to do this depends on your version of Excel. In more recent versions, it will be on the Get & Transform tab on the Data Ribbon and may say something like From Text/CSV.
If you need to automate this, you can record a VBA macro while doing it.
I entered the values you listed above in a document using Notepad, and saved it as a csv file.
I then used the above method and got this result:
For me, the best solution was to use Workbook.OpenText to open the downloaded files and use the fieldinfo parameter to force the relevant columns to be formatted as text. The only trick is to make sure the downloaded file name has extension .txt, not.csv. For unknown reasons, VBA will not respect the fieldinfo parameter to open files with the .csv extension, regardless of the file content.