简体   繁体   English

VBA文件夹路径在文件之前一步

[英]VBA Folder Path One Step Before File

I want to save few template files that I create during running of the code in VBA. 我想保存在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. 我有一个名为Path的字符串变量,其值为thisworkbook.path。 I wnat to name this new string variable PathBefore . 我将这个新的字符串变量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: 用以下三行替换Initialize()子句中的最后一行:

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:\\ 如果工作簿位于根目录中,例如c:\\,则上面的代码将返回双引号(“”)而不是错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM