Excel-VBA重命名并保存到备用目录,无需用户干预

时间:2016-09-06 21:23:41

标签: excel vba excel-vba

我有一系列excel电子表格,需要更改文件名并保存到备用路径。我遇到了试图自行尝试此问题的墙。

原始文件名: A0001_lp_profile.csv (A000#并不总是A0001)

新文件名: A0001.RecentlyOpenedFiles.LNK.xlsx

重命名期间前五个字符不会改变。

原始路径: E:\ Backup \ VSNMM-01691 \ Cases \ VSNMM-01691.A0001 \ Exports_fileFolderOpening

新路径: E:\ Backup \ VSNMM-01691 \ Reports

VSNMM-01691并不总是在路径中,并且经常更改为类似格式的内容。 “E:\ Backup \”将始终是路径的开头。

1 个答案:

答案 0 :(得分:0)

这应该可行,只需确保我的路径和文件名模式正确:

Dim file As Variant
Dim wb As Workbook
Dim originalpath As String, newpath As String

originalpath = "E:\Backup\VSNMM-01691\Cases\VSNMM-01691.A0001\Exports_fileFolderOpening\"
newpath = "E:\Backup\VSNMM-01691\Reports\"

file = Dir(originalpath)

'loop through files in original folder
While (file <> "")

    'match filename with pattern (# means one number, so 4 single numbers) change this if i did it wrong
    If file Like "A####_lp_profile.csv" Then

        'open the csv file
        Set wb = Workbooks.Open(originalpath & file)

        'save in new path as xlsx (without the Fileformat, the file will be unreadable
        wb.SaveAs newpath & Left(file, 5) & ".RecentlyOpenedFiles.LNK.xlsx", ThisWorkbook.FileFormat

        'close workbook in original path, discard changes
        wb.Close False

        'clear variable
        Set wb = Nothing
    End If

    'next file
    file = Dir
Wend