I am trying to write a VB script that concatenates data together into a url string and then I want it to copy down into all the rows for that column. I've got the fill down code working okay but when I try to add the concatenate I keep getting a syntax error so I'm not sure what I'm doing wrong. I have tried two versions and they both give me syntax errors on the final line of script (right side):
Script Version 1:
Sub SetSurveyLink()
' SetSurveyLink Macro
Dim lngLastRow As Long
lngLastRow = Cells(Rows.Count, "A").End(xlUp).Row
Range("C3:C" & lngLastRow).Value = EVALUATE("https://domainname.com/survey/?PartName=" & 'Client List'!B1 & "&ClientID="&B2)
End Sub
Script Version 2:
Sub SetSurveyLink()
' SetSurveyLink Macro
Dim lngLastRow As Long
lngLastRow = Cells(Rows.Count, "A").End(xlUp).Row
Range("C3:C" & lngLastRow).Value = CONCATENATE("https://domainname.com/survey/?PartName=",'Client List'!B1,"&ClientID=",B2)
End Sub
The 'concatenate' string gives me the correct value when used in a cell (i.e. not as part of a script) but I just can't get it to work in the script. See anything that I'm missing in my syntax?
THANK YOU!
Any double-quote marks within a string need to be escaped to be double double-quote marks so, if
"https://domainname.com/survey/?PartName=" & 'Client List'!B1 & "&ClientID="&B2
worked within Excel, it becomes
""https://domainname.com/survey/?PartName="" & 'Client List'!B1 & ""&ClientID=""&B2
and then you need to enclose that within double-quote marks to make it a string literal within VBA, i.e.
"""https://domainname.com/survey/?PartName="" & 'Client List'!B1 & ""&ClientID=""&B2"
Related
I am trying to create a VBA macro to automatically label each record in Sheet1 with the correct category based on Sheet2. However, I am getting this error:
Run-time Error '1004': Invalid number of arguments.
When I debug, it seems to point to the line of code noted below.
The codes are as follow in a module tab:
Sub X()
Dim i As Long
Dim r As Long
Dim s As Variant
For i = 1 To Worksheets("Sheet1").Rows.Count
Dim arr() As String
For r = 1 To Worksheets("Sheet2").Rows.Count
' the next line is where i get the error
If Application.IsNumber(Application.Search("Sheet2!A$" & i & ",Sheet1!A" & r)) Then
ReDim Preserve arr(i)
arr(i) = Worksheets("Sheet2").Cells(r, 2)
End If
Next r
For Each s In arr()
Dim b As Long
b = Application.Match(s & ",A1:M1")
Worksheets("Sheet1").Cells(r - 1, b).Value = "Y"
Next s
Erase arr()
Next i
End Sub
Sheet1 shows the special requests to be tagged/labelled with Y in the preceding columns
Sheet2 containing the primary keywords to search for and label the text in Sheet1 with Y if it is found
If you use Application.SomeFunction you should use the proper qualifier WorksheetFunction so you get the intellisense for the required parameters / arguments.
E.g typing Application.WorksheetFunction.Search( instead of Application.Search( will show that you need two string arguments in your Search() function, and you only provide one - but the one you provide does have a comma in it so I suspect you're joining the two arguments together in to one string by mistake.
You could try
("Sheet2!A$" & i, "Sheet1!A" & r)
In VBA this will become (Sheet2.Range("A1"), Sheet1.Range("A9"))
Instead of
("Sheet2!A$" & i & ",Sheet1!A" & r)
Which would resolve to ("Sheet2!A1,Sheet1!A9")
Note the difference - the latter is a single string which is trying to pass to Search() and the first is two separate Range arguments separated by a comma.
Just looking at the line you hightlighted.
If Application.IsNumber(Application.Search("Sheet2!A$" & i & ",Sheet1!A" & r)) Then
It appears:
Application.Search("Sheet2!A$" & i & ",Sheet1!A" & r)
requires two inputs. See link below
expression.Search (Arg1, Arg2, Arg3)
But, I could be wrong.
So the easiest way to debug would be to split up that line and see what is causing the error.
(1) Pull out this part of that line:
Application.Search("Sheet2!A$" & i & ",Sheet1!A" & r)
(2) Does that work? Does it return an argument that makes sense?
If not, fix that line. If so, move on to just the part below with a hardcoded input in the format from part 1 above. From there you can isolate which part of the line is giving you issues and verify each function is getting the right format input.
Application.IsNumber()
I'm trying to insert a Vlookup formula on some filtered data but I've run into a few errors. Below is the code I'm using. (Not all of it, just the section with the issue)
'Sells
Dim SellData As Worksheet
Set SellData = Transactions.Sheets("SellData")
Dim lrSell As Long
lrSell = SellData.Cells(Rows.Count, "H").End(xlUp).Row
Dim SellDataRange As Range
Set SellDataRange = SellData.Range("A1:CW" & lrSell)
PrVFormat = Format$(Transactions.Sheets("others").Range("B2").Value, "dd-mmm-yy")
SellDataRange.AutoFilter Field:=8, Criteria1:=PrVFormat
lrSellFilter = SellData.Cells(Rows.Count, "H").End(xlUp).Row
With SellData.Range("CW2:CW" & lrSellFilter).SpecialCells(xlCellTypeVisible)
.Cells.FormulaR1C1 = "=VLOOKUP(RC[-12],'[OtherWorkbook.xlsx]new'!$A:$K,11,FALSE)" '1004 error
SellData.Calculate
SellDataRange.AutoFilter Field:=8
SellData.Range("CW1:CW" & lrSell).Copy
SellData.Range("CW1").PasteSpecial xlPasteValues
End With
The line I'm having an issue with is
.Cells.FormulaR1C1 = "=VLOOKUP(RC[-12],'[OtherWorkbook.xlsx]new'!$A:$K,11,FALSE)"
If I leave the $, I receive a 1004 error. If I remove the $, the formula end up like this
=VLOOKUP(CK1578,'[OtherWorkbook.xlsx]new'!A:(K),11,FALSE)
'Notice the parenthesis around the K. That shouldn't be there.
Thank you in advance for your assistance
You cannot mix R1C1 and A1 nomenclature.
.Cells.FormulaR1C1 = "=VLOOKUP(RC[-12],'[OtherWorkbook.xlsx]new'!C1:C11,11,FALSE)"
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 find and replace hundreds of misnamed field names (cell names) in a large excel financial model. I'm trying to build this macro subroutine to find a given field name and replace it with the correct field name.
Sub FindReplaceFieldName()
Dim orgFieldName As String
Dim replFieldName As String
orgFieldName = "CAN"
replFieldName = "Canada"
Application.Goto Reference:=orgFieldName
With ActiveWorkbook.names(orgFieldName)
.Name = replFieldName
.RefersToR1C1 = "=Sheet1!(" & activeCell.row & ";" & activeCell.Column &")".Comment = ""
End With
ActiveWorkbook.Save
End Sub
The field name is found and replaced, but a Runtime error 1004 is thrown here
"=Sheet1!(" & activeCell.row & ";" & activeCell.Column &
")"
"The formula you typed contains an error." and so on.
I'm not familiar with VBA syntax, so a 2nd pair of experienced eyes would be helpful.
SOLVED: The correct syntax should be
.RefersToR1C1 = "=Sheet1!R" & activeCell.row & "C" & activeCell.Column & ""
Forgive me if wrong, but are you not approaching this sideways? You want to change the existing names not amend the locations; Ergo, use a mapping to rename the existing.
For example, use a dictionary to rename (you could use other structures); I wanted to leverage the .Exists of a dictionary so only attempted valid substitutions. You could even loop a range in the sheet to populate your dictionary. Or read the range straight into an array and dump the array into the dictionary as key/values.
Code:
Option Explicit
Public Sub RenameNamedRanges()
Dim currName As Name
Dim replaceDict As Object
Set replaceDict = CreateObject("Scripting.Dictionary")
replaceDict.Add "CAN", "Canada"
replaceDict.Add "FR", "France"
replaceDict.Add "DE", "Deutschland"
For Each currName In ThisWorkbook.Names
If replaceDict.Exists(currName.Name) Then
currName.Name = replaceDict(currName.Name)
End If
Next currName
End Sub
Before:
After:
To troubleshoot issues like this, where you're building a string to be used elsewhere, troubleshoot by looking at the problem string just before the error is caused.
In this case, you could add a line just before the line where you get the error:
Debug.Print "=Sheet1!(" & activeCell.row & ";" & activeCell.Column & ")"
...then, when you run your code and get the error, go to the Immediate Window (Ctrl+G) and see what Excel thinks you mean.
Are you able to see your error now?
That being said, you must have posted your code incorrectly, since I can't get it to run at all (to get an Error 1004) since this line is wonky:
.RefersToR1C1 = "=Sheet1!(" & activeCell.row & ";" & activeCell.Column &")".Comment = ""
If I replace the row and column numbers you're trying to insert with 1234 then it would read:
.RefersToR1C1 = "=Sheet1!(1234;1234)".Comment = ""
I can't give an absolute solution without knowing more about what you're trying to do, but obviously that is an invalid command (and likely not what you intended).
Note that ActiveCell.Row and ActiveCell.Column both return numbers, and that Sheet1!(1,1) is not how we refer to a cell in Excel.
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 &