Excel Error:1004 - Trying to write cell formula - vba

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,"

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

VBA Formula: Variable File Name and Variable Sheet Name

I am trying to create a cell reference to a cell in another workbook. In my code below, I am using a variable for workbook name and sheet name.
SourceFileNamePath = Path and name of workbook I am linking to
SourceTab = Tab in the workbook I want to link to
Though the code runs fine, the formula generated is not working. Does anyone have any thoughts on whether I am referencing SourceFileNamePath and SourceTab correctly?
Code is below:
Cells(destStartRow, destStartCol).FormulaR1C1 = "='[" & SourceFileNamePath & "]" & SourceTab & "'!R" & sourceStartRow & "C" & sourceStartCol
The format to access a cell in a sheet in an external workbook is
'path\[filename]sheetname'!cell_reference
so if you have a variable called SourceFileNamePath containing the path and filename (e.g. "C:\Temp\Data\Book1.xlsx") then you need to separate the filename from the path.
You could use something like:
SourceFileNamePath = "C:\Temp\Data\Book1.xlsx" ' or however you set that variable
SourceTab = "Sheet1" ' or however you set that variable
Dim SourceFilePath As String
Dim SourceFileName As String
SourceFilePath = Left(SourceFileNamePath, InStrRev(SourceFileNamePath, Application.PathSeparator))
SourceFileName = Mid(SourceFileNamePath, InStrRev(SourceFileNamePath, Application.PathSeparator) + 1)
Cells(destStartRow, destStartCol).FormulaR1C1 = "='" & SourceFilePath & "[" & SourceFileName & "]" & SourceTab & "'!R" & sourceStartRow & "C" & sourceStartCol
Note: If either the path or the filename contains any single-quotation marks (e.g. if the filename was Sukhbir's test file.xlsx) then it will need to be escaped (i.e. each single-quotation mark needs to be replaced by two single-quotation marks). This can be achieved by using the Replace function, e.g.:
Cells(destStartRow, destStartCol).FormulaR1C1 = _
"='" & Replace(SourceFilePath, "'", "''") & _
"[" & Replace(SourceFileName, "'", "''") & "]" & _
SourceTab & "'!R" & sourceStartRow & "C" & sourceStartCol

Excel VBA CountIF To Search For String Array

How can I use the COUNTIF() function to count only certain text strings that exist in the range?
I tried to use the below, but I get an error of
Syntax error
This is the syntax I attempted
Dim worksheetmaster As String = "Master"
Dim worksheettocheck As String = "New"
Dim softcount As Int, i As Long, hardcount As Int
softcount = Evaluate("=COUNTIF(Range('" & worksheettocheck & "'!A:A'" & worksheetmaster & "'!A" & i & ")"Soft")")
hardcount = Evaluate("=COUNTIF(Range('" & worksheettocheck & "'!A:A'" & worksheetmaster & "'!A" & i & ")"Hard")")
EDIT
I tried to use this syntax without the Range and am still getting the error
hardcount = Evaluate("=COUNTIF('" & worksheettocheck & "'!A:A'" & worksheetmaster & "'!A" & i & ")"Hard"")
To match in column A with Hard in column B, this is how it should be:
hardcount = Application.Evaluate("COUNTIFS('" & worksheettocheck & "'!A:A,'" & worksheetmaster & "'!A" & i & ",'" & worksheettocheck & "'!B:B, ""Hard"")")
softcount = Application.Evaluate("COUNTIFS('" & worksheettocheck & "'!A:A,'" & worksheetmaster & "'!A" & i & ",'" & worksheettocheck & "'!B:B, ""Soft"")")
Your first syntax errors are here:
Dim worksheetmaster As String = "Master"
Dim worksheettocheck As String = "New"
You can't do that. Instead, you would need to use:
Dim worksheetmaster As String
Dim worksheettocheck As String
worksheetmaster = "Master"
worksheettocheck = "New"
Even better would be to assign them to point diectly at the worksheets, but let's work with your code as much as possible instead of totally rewriting it.
For the countif, you cannot join ranges that way. You haven't even assigned a value to i, but assuming i = 1, your code:
softcount = Evaluate("=COUNTIF(Range('" & worksheettocheck & "'!A:A'" & worksheetmaster & "'!A" & i & ")"Soft")")
evaluates to total nonsense in VBA:
softcount = Evaluate(=COUNTIF(Range('New'!A:A'Master'!A1)Soft))
Now, from what I can tell, what you are trying to do is to count how many times the value in cell Master!A & i appears in the range New!A:A, depending whether Master!A & i="Soft" or Master!A & i="Hard". So let's see if we can find code that will do that.
For data we enter "Soft" into Master!A1 and "Hard" into Master!A2. Then we enter random "Soft" or "Hard" into various cells in the column New!A:A.
Now your code looks like this:
Dim worksheetmaster As String
Dim worksheettocheck As String
Dim softcount As Long, i As Long, hardcount As Long
worksheetmaster = "Master"
worksheettocheck = "New"
i = 1
softcount = Application.CountIf(Sheets(worksheettocheck).Range("A:A"), Sheets(worksheetmaster).Range("A" & i).Value)
i = 2
hardcount = Application.CountIf(Sheets(worksheettocheck).Range("A:A"), Sheets(worksheetmaster).Range("A" & i).Value)
This is inefficient and limited, but it retains as much of your original code as possible, and it works.
Edited to add: if "Hard" is in Master!B & i instead of A & i then the code becomes:
i = 1
softcount = Application.CountIf(Sheets(worksheettocheck).Range("A:A"), Sheets(worksheetmaster).Range("A" & i).Value)
hardcount = Application.CountIf(Sheets(worksheettocheck).Range("A:A"), Sheets(worksheetmaster).Range("B" & i).Value)

how to use variable containing strings in formula 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 "

Move file into dynamically created folder with VB Script

I am working on a backup script in VBS that creates a folder and then copies a powerpoint file into the most recently created folder.
Everything works great except MoveFile command at the bottom
Here is what I got so far (the bottom code is most important but just so everyone can understand where I am coming from):
sourceDir = "T:\Team"
destinationDir = "T:\Team\Archive\Archive"
const OverwriteExisting = True
intNum = 1
strDirectory = destinationDir & "_" & replace(date,"/",".") & "_" & intNum
'This checks if the folder exists and if not it will create a folder with the date and increment the folder name incase there are multiple updates in a single day.
if not filesys.FolderExists(destinationDir) then
While filesys.FolderExists(destinationDir & "_" & replace(date,"/",".") & "_" & intNum) = True
intNum = intNum + 1
Wend
Set archivefolder = filesys.CreateFolder(destinationDir & "_" & replace(date,"/",".") & "_" & intNum)
Else
Set archivefolder = filesys.CreateFolder(destinationDir)
Set objFolder = fso.CreateFolder(strDirectory)
End if
Dim thisday, thisdayy, thisdayyy
Today_Date()
' This is the problem code
filesys.MoveFile "T:\Arriva\Project_Organigram_" & thisday & "." & thisdayy & "." & thisdayyy & ".pptm", "destinationDir & "\" & Project_Organigram_" & thisday & "." & thisdayy & "." & thisdayyy & ".pptm"
Function Today_Date()
thisday=Right(Day(Date),2)
thisdayy=Right("0" & Month(Date),2)
thisdayyy=Right("0" & Year(Date),2)
End Function
This results in a folder being created as "T:\Team\Archive\Archive_03.12.2014_1
My goal is to be able to move the file in T:\Team to the dynamically created folder above.
Everything works great until the MoveFile part. The destination is the part throwing a "type mismatch" at the line where I define the strDirectory
I am just learning this type of programming so please let me know if I can provide any further details!
Thank you in advance!
You have a couple syntax errors with your quotes that are cancelling each other out. Change your line to this:
filesys.MoveFile "T:\Team\Project_Organigram_" & thisday & "." & thisdayy & "." & thisdayyy & ".pptm", "destinationDir" & "_" & replace(date,"/",".") & "_" & intNum & "\" & "Project_Organigram_" & thisday & "." & thisdayy & "." & thisdayyy & ".pptm"