簡體   English   中英

VBA文件夾路徑在文件之前一步

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM