【问题标题】:Rename an excel file and save it to a relative path with VBA重命名 excel 文件并使用 VBA 将其保存到相对路径
【发布时间】:2017-07-15 00:18:16
【问题描述】:

我有一个通过我录制的宏进行格式化的工作簿。宏当前重命名文件并将其保存到恒定路径,但我需要它重命名文件并将其保存到相对路径,以便其他队友可以使用它。有什么建议吗?

这是活动文件

Windows("Manual Reconciliation Template.xlsm").Activate

这是固定路径

ActiveWorkbook.SaveAs FileName:= _
        "C:\Users\e6y550m\Documents\MANUAL RECS\Manual Reconciliation Template.xlsm", _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

当前代码:

Sub Name_And_Save_Report()
'
' TO NAME, DATE AND SAVE THE REPORT AFTER IT HAS BEEN WORKED.
'
    Windows("Manual Reconciliation Template.xlsm").Activate
    Dim thisWb As Workbook
    Dim fname

    fname = InputBox("Enter your name (example-John):")    
    Set thisWb = ActiveWorkbook
    Workbooks.Add
    ActiveWorkbook.SaveAs FileName:=thisWb.Path & "\" & fname & "_Manual Recon" & " " & Format(Date, "MM.DD.YY") & ".xlsx"
    ActiveWorkbook.Close savechanges:=False
    Windows("Manual Reconciliation Template.xlsm").Activate
    ActiveWorkbook.Close savechanges:=False
End Sub

【问题讨论】:

  • “相对路径”?相对于什么? (或者你的意思是某个地方的共享目录?)显然答案是用你想要的任何路径替换thisWb.Path,但问题中没有任何内容可以建议那将是什么,所以很难帮助你.

标签: vba excel


【解决方案1】:

因此,您将在每个个人文件夹中粘贴包含上述代码的工作簿副本。当他们打开工作簿时,您希望它重命名为:
>_Manual Recon >.xlsx

我假设您希望将原始文件保留在那里,以便他们可以打开它并为第二天创建一个新的 xlsx,但如果文件已经存在,则不要创建文件(以防他们在一天内打开 xlsm 两次)。

需要考虑的另一点 - 他们的个人文件夹是否有他们的名字?
例如。 G:\MMS Trade Payables\John

我注意到您在代码中设置了一个变量 thisWb 等于 ActiveWorkbook
您可以只使用ThisWorkbook,它始终指代运行代码的工作簿。

所以有了这些假设,试试这个代码:

Sub Name_And_Save_Report()

    Dim fName As String
    Dim sNewFile As String

    'Get the folder name.
    fName = GetParentFolder(ThisWorkbook.Path)

    'Could also get the Windows user name.
    'fName = Environ("username")

    'Or could get the Excel user name.
    'fname = application.username

    'Or could just ask them.
    'fname = InputBox("Enter your name (example-John):")

    sNewFile = ThisWorkbook.Path & Application.PathSeparator & _
        fName & "_Manual Recon " & Format(Date, "mm.dd.yy") & ".xlsx"

    If Not FileExists(sNewFile) Then
        'Turn off alerts otherwise you'll get
        '"The following features cannot be saved in macro-free workbooks...."
        '51 in the SaveAs means save in XLSX format.
        Application.DisplayAlerts = False
        ThisWorkbook.SaveAs sNewFile, 51
        Application.DisplayAlerts = True
    End If

End Sub

Public Function FileExists(ByVal FileName As String) As Boolean
    Dim oFSO As Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    FileExists = oFSO.FileExists(FileName)
    Set oFSO = Nothing
End Function

Public Function GetParentFolder(ByVal FilePath As String) As String
    Dim oFSO As Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    GetParentFolder = oFSO.GetFolder(FilePath).Name
    Set oFSO = Nothing
End Function

我将把它留在这里作为我的第一个答案:

你的意思是这样的吗?
使用FileSystemObject递归获取父文件夹名称。

Sub Test()

    MsgBox ThisWorkbook.Path & vbCr & RelativePath(ThisWorkbook.Path, 2)

    'Will return "C:\Users\e6y550m" - step back 2 folders.
    MsgBox RelativePath("C:\Users\e6y550m\Documents\MANUAL RECS\", 2)

    'Your line of code:
    'ActiveWorkbook.SaveAs FileName:=RelativePath(thisWb.Path, 2) & "\" & fname & "_Manual Recon" & " " & Format(Date, "MM.DD.YY") & ".xlsx"

End Sub

'FilePath - path to file, not including file name.
'GetParent - the number of folders in the path to go back to.
Public Function RelativePath(FilePath As String, Optional GetParent As Long) As String
    Dim oFSO As Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    'If rightmost character is "\" then we've reached the root: C:\
    If GetParent = 0 Or Right(FilePath, 1) = Application.PathSeparator Then

        RelativePath = oFSO.GetFolder(FilePath)

        'If we've reached the root then remove the "\".
        If Right(RelativePath, 1) = Application.PathSeparator Then
            RelativePath = Left(RelativePath, Len(RelativePath) - 1)
        End If

    Else

        'GetParent is greater than 0 so call the RelativePath function again with
        'GetParent decreased by 1.
        RelativePath = RelativePath(oFSO.GetParentFolderName(FilePath), GetParent - 1)

    End If
    Set oFSO = Nothing
End Function

【讨论】:

  • Darren Bartrup,您的第一个答案非常有效!我也会尝试第二个,因为我想完全理解两组代码。感谢您提供详细的注释,因为它们使我能够完全理解代码。再次感谢!
【解决方案2】:

如果我的问题不清楚,我深表歉意;我充其量是VBA新手。

'这是当前已经打开的文件,

Windows("Manual Reconciliation Template.xlsm").Activate

' 我想与我的队友分享这个文件,以便他们可以使用它。他们都有不同的文件夹。我将把这个工作簿的副本放在他们的每个文件夹中。当他们使用其个人文件夹中的副本时,宏需要重命名工作簿并将重命名的副本保存在他们的个人文件夹中。因此,宏需要重命名工作簿并将其保存在其文件夹中的代码,而无需定义路径。共享驱动器路径是 G:\MMS Trade Payables。在 MMS Trade Payables 文件夹中是个人文件夹。我认为代码只需要激活当前已打开的工作簿,将其重命名并将其作为 .xlsx 而不是 .xlsm 保存在当前文件夹中。

当前代码:

Sub Name_And_Save_Report()
'
' TO NAME, DATE AND SAVE THE REPORT AFTER IT HAS BEEN WORKED.
'
    Windows("Manual Reconciliation Template.xlsm").Activate
    Dim thisWb As Workbook
    Dim fname

' Will use the fname variable to add the associates name to the file name (ex:If the associate enters Mark into the inputbox, fname will = Mark).  
    fname = InputBox("Enter your name (example-John):")  

' Makes thisWb = "Manual Reconciliation Template.xlsm".
    Set thisWb = ActiveWorkbook     
    Workbooks.Add

' Saves the active workbook ("Manual Reconciliation Template.xlsm") to the path of thisWb and renames the workbook by adding the fname value and the current date (ex: if the associate entered Mark as the value of fname, "Manual Reconciliation Template.xlsm" becomes "Mark_Manual Recon 7.14.17.xlsx").
    ActiveWorkbook.SaveAs FileName:=thisWb.Path & "\" & fname & "_Manual Recon" & " " & Format(Date, "MM.DD.YY") & ".xlsx" 

' Closes the renamed workbook.
    ActiveWorkbook.Close savechanges:=False

' Calls the original workbook and closes it.
    Windows("Manual Reconciliation Template.xlsm").Activate
    ActiveWorkbook.Close savechanges:=False
End Sub

当然,这可能是完全错误的,因为我是 VBA 新手。

【讨论】:

  • 您应该编辑您的原始问题以包含此额外信息并将其作为答案删除。
猜你喜欢
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2021-05-24
相关资源
最近更新 更多