VBA Formula: Variable File Name and Variable Sheet Name - vba

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

Related

VBA lookup refer to first sheet in workbook not "Sheet1"

How would I change the below lookup to refer to the first sheet in the workbook and not 'Sheet 1'?
.Range("I15:I" & lastRow).FormulaR1C1 = _
"=IF(VLOOKUP(RC[-8],[" & combinedWorkbook.Name & "]Sheet1!C1:C2,1,TRUE)=RC[-8],VLOOKUP(RC[-8],[" & combinedWorkbook.Name & "]Sheet1!C1:C2,2,TRUE),NA())"
Thanks
You are concatenating already the workbook name into the formula. The same way you could concatenating the name of the first worksheet too. The first worksheet is the first sheet in workbook's Worksheets collection.
So combinedWorkbook.Worksheets(1).Name would be the name of the first worksheet in workbook combinedWorkbook.
But names could containing spaces like "My Worksheet Name". Then the reference itself must be within single quotes like 'My Worksheet Name'!A1.
So all together:
.Range("I15:I" & lastRow).FormulaR1C1 = _
"=IF(VLOOKUP(RC[-8],'[" & combinedWorkbook.Name & "]" & combinedWorkbook.Worksheets(1).Name & "'!C1:C2,1,TRUE)=RC[-8],VLOOKUP(RC[-8],'[" & combinedWorkbook.Name & "]" & combinedWorkbook.Worksheets(1).Name & "'!C1:C2,2,TRUE),NA())"
if you are going to re-use it then I would declare:
Dim first_sheet As String
first_sheet = combinedWorkbook.Sheets(1).Name
And then use it in your code like this:
.Range("I15:I" & lastRow).FormulaR1C1 = _
"=IF(VLOOKUP(RC[-8],[" & combinedWorkbook.Name & "] & first_sheet & !C1:C2,1,TRUE)=RC[-8],VLOOKUP(RC[-8],[" & combinedWorkbook.Name & "] & first_sheet & !C1:C2,2,TRUE),NA())"
This is really a small example how to refer to the first worksheet.
Take the name of the first worksheet and save it as a variable, using the .Name property.
Concatenate the variable in the formula:
Public Sub TestMe()
Dim wks1 As String
wks1 = Worksheets(1).Name
'worksheets should not contains spaces! :) left and right
Worksheets(1).Name = Trim(wks1)
Range("I15:I20").FormulaR1C1 = "=" & wks1 & "!R1C1"
End Sub

Changing Day and Month to DD and MM format in VBA

To give some context here, I have a dat file that I am trying to save as an xlsx on my Q drive. I know that the majority of the code works (I've tested it), so I don't want to completely change it, but the formatting as I explain below is what I need help with. The following code is in workbook1 and it is referencing workbook2. Cell D3 in workbook one is a date formula but unfortunately, the FileDay and FileMonth code will only pull in a single "d" or "m" when what I want is it to pull in days and months in the "dd" and "mm" format. Since the code below is trying to find a file in this format: "yyyy_mm_dd" but FileDay and FileMonth are only pulling in "d" and "m", it will only work during part of the year. What is the piece of code that I am missing to pull in the correct formatting from cell D3?
Dim FName As String, FPath As String
Dim wkb1 As Workbook, wkb2 As Workbook
Set wkb1 = ThisWorkbook
FileDay = Day(Range("D3"))
FileMonth = Month(Range("D3"))
FileYear = Year(Range("D3"))
FPath = "Q:\MyFolder"
FName = "MyFile_" & FileYear & "_" & FileMonth & "_" & FileDay & ".xlsx"
Set wkb2 = Workbooks("MyFile_" & FileYear & "_" & FileMonth & "_" & FileDay
& ".dat")
With wkb2
.SaveAs Filename:=FPath & "\" & FName
.Close True
End With
End Sub
Assuming these variables are Strings, use the Format$ function.
FileDay = Format$(Day(Range("D3")), "00")
FileMonth = Format$(Month(Range("D3")), "00")
FileYear = Format$(Year(Range("D3")), "0000")
Alternatively, do it all at once:
= Format$(Range("D3"), "YYYY_MM_DD")

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

Using .formula using vba excel

I'm trying link to workbooks. Then Remove the link. The formula is working fine when the Full path is given but fails the moment a string is passed. In the below vba i'm trying to give the name of the location of the files from a cell value in Sheet1.
'Location of Template and Country
Cntryloc = """" & Sheet1.Range("B5") & """"
Debug.Print Cntryloc
TempLoc = "" & Sheet1.Range("B11") & ""
Finaltemplloc = Sheet1.Range("B17")
i=2
'Getting the name of excel Sheet
CntryExcel = Sheet1.Range("C5")
TempLoc = "" & Sheet1.Range("B11") & ""
Workbooks.Open TempLoc & "\" & "Bank" & ".xlsx", True, False
Workbooks("" & FName & ".xlsx").Activate
ActiveWorkbook.Unprotect Password:="Tall.Trees"
Worksheets("Template").Unprotect Password:="Tall.Trees"
Worksheets("Template").Range("D14").Formula = "='&"["&CntryExcel&"]Dump"&"'"&"!"&"$A$" & i""
ActiveWorkbook.BreakLink Name:=Cntryloc, Type:=xlExcelLinks
Worksheets("Template").Protect Password:="Tall.Trees"
ActiveWorkbook.Protect Password:="Tall.Trees"
'Location for Final Output
ActiveWorkbook.SaveAs Filename:=Finaltemplloc & "\" & Bank.xlsx
ActiveWorkbook.Close
try with this
Worksheets("Template").Range("D14").Value = "='[" & CntryExcel & "]Dump'!" & "$A$" & i & ActiveWorkbook.BreakLink & "Name:=" & Cntryloc & ", Type:=" & xlExcelLink
try this
Worksheets("Template").Range("D14").Formula = "='[" & CntryExcel & "]Dump!$A$" & "i"
that should fix the formula input
but check for CntryExcel to hold a workbook name and not a sheet name as per your comment preceeding its initialization ('Getting the name of excel Sheet)

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