如何更改文件命名字符串的顺序?

时间:2019-03-30 05:07:10

标签: excel vba

对于在两个不同的位置保存和创建文件备份版本,我有以下工作效果很好,但是我想更改文件名中字符串的顺序。首先是文件名,然后是日期和时间戳。到目前为止没有成功。

Sub SaveToLocations()
' Saves active file to current plus two other backup locations, appends date and time in front of file name

    Dim datim As String
    datim = Format(CStr(Now), "yyyy_mm_dd_hh_mm_ss_")

    ActiveWorkbook.SaveCopyAs "I:\FilesBackupCS\" & datim & ActiveWorkbook.Name
    ActiveWorkbook.SaveCopyAs "E:\Coconut Shade Docs\FilesBackupCS\" & datim & ActiveWorkbook.Name
    ActiveWorkbook.Save
End Sub

1 个答案:

答案 0 :(得分:0)

您可以使用以下三个功能来实现

Function FileNameNoExtensionFromPath(strFullPath As String) As String

    Dim intStartLoc As Integer
    Dim intEndLoc As Integer
    Dim intLength As Integer

    intStartLoc = Len(strFullPath) - (Len(strFullPath) - InStrRev(strFullPath, "\") - 1)
    intEndLoc = Len(strFullPath) - (Len(strFullPath) - InStrRev(strFullPath, "."))
    intLength = intEndLoc - intStartLoc

    FileNameNoExtensionFromPath = Mid(strFullPath, intStartLoc, intLength)

End Function
Function FileExtensionFromPath(ByRef strFullPath As String) As String
    FileExtensionFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "."))
End Function
Function myFileName(ByVal wkb As Workbook, addString As String) As String
    myFileName = FileNameNoExtensionFromPath(wkb.FullName) & addString & "." & FileExtensionFromPath(wkb.FullName)
End Function

在您的代码中

ActiveWorkbook.SaveCopyAs "I:\FBackupCS\" & myFileName(ActiveWorkbook, datim)
ActiveWorkbook.SaveCopyAs "E:\CS Docs\FBackupCS\" & myFileName(ActiveWorkbook, datim)

PS,我认为您可以将其与其他post

的答案结合起来