I want to save few template files that I create during running of the code in VBA. I want to save them in specific folders in the filder path one step before the active workbook. How can I get the path dynamically in the code?
I have string variable named Path with the value thisworkbook.path. I wnat to name this new string variable PathBefore
.
Sub Initialize()
Set MainWB = ThisWorkbook
Set MainSheet = MainWB.Worksheets("Main")
SLRow = MainWB.Worksheets("SAP").Cells(Rows.Count, "A").End(xlUp).Row
ELRow = MainWB.Worksheets("Employees").Cells(Rows.Count, "A").End(xlUp).Row
MLRow = MainSheet.Cells(Rows.Count, "A").End(xlUp).Row
ListLR = MainWB.Worksheets("Lists").Cells(Rows.Count, "A").End(xlUp).Row
Set emp = MainSheet.Range("A1:A" & MLRow)
Path = ThisWorkbook.Path 'here is path variable
End Sub
Sub Create_Workbook()
'Create new workbook and copy the data into it in an Export folder
Call Initialize
Dim DiklaWB As Workbook
Dim StandartWB As Workbook
Dim tmpWB As Workbook
'Standart 02 Workbbok
With MainWB.Worksheets("Employees")
.Range("$A$1:$M$" & ELRow).AutoFilter Field:=13, Criteria1:=MainWB.Worksheets("Lists").Range("I1")
.Range("$A$2:$M$" & ELRow).SpecialCells(xlCellTypeVisible).Copy
End With
Set StandartWB = Application.Workbooks.Add
StandartWB.Worksheets(1).Cells(2, 1).PasteSpecial xlPasteValues
MainWB.Worksheets("Employees").Range("A1:M1").Copy
StandartWB.Worksheets(1).Cells(1, 1).PasteSpecial xlPasteValues
StandartWB.SaveAs Filename:=Path & "\Export\ 02 .xlsx" 'I want to save it in the folder before thisworkbok.path
StandartWB.Close
End Sub
You could use
Dim pathChunks As Variant
pathChunks = Split(ThisWorkbook.Path, "\")
ReDim Preserve pathChunks(1 To Ubound(pathChunks)-1)
Path = Join(pathChunks, "\")
Or
Path = Left(ThisWorkbook.Path, InstrRev(ThisWorkbook.Path, "\") - 1)
Replace the last line in your Initialize() sub with the following three lines:
With CreateObject("Scripting.FileSystemObject")
Path = .GetParentFolderName(ThisWorkbook.Path)
End With
The above code will return double quotes ("") rather than error if the workbook is in a root directory, like c:\\
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.