[英]VBA Folder Path One Step Before File
我想保存在VBA中运行代码期间创建的一些模板文件。 我想将它们保存在活动工作簿之前一步到特定路径的文件夹中。 如何在代码中动态获取路径?
我有一个名为Path的字符串变量,其值为thisworkbook.path。 我将这个新的字符串变量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
你可以用
Dim pathChunks As Variant
pathChunks = Split(ThisWorkbook.Path, "\")
ReDim Preserve pathChunks(1 To Ubound(pathChunks)-1)
Path = Join(pathChunks, "\")
要么
Path = Left(ThisWorkbook.Path, InstrRev(ThisWorkbook.Path, "\") - 1)
用以下三行替换Initialize()子句中的最后一行:
With CreateObject("Scripting.FileSystemObject")
Path = .GetParentFolderName(ThisWorkbook.Path)
End With
如果工作簿位于根目录中,例如c:\\,则上面的代码将返回双引号(“”)而不是错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.