尝试使用包含随机数的原始名称来识别和重命名文件

Trying to identify and rename a file with an original name that contains a random number

您好,我正在尝试重命名文件夹中的文件(包含多个相似文件),但即使使用通配符方法也很难识别它。原始文件名如下所示:“2018_02_26_20180228_XXXXXX_GDW_Audit_CView_Report.txt”所以我识别它的唯一方法是知道名称的一部分(“_GDW_Audit_CView_Report.txt”),因为日期在多个文件中是相同的。我编写了以下代码,当我尝试 运行 时会出现 Path/File 访问错误。任何帮助将不胜感激。

Option Explicit
Sub HGDW_WKD()

    Dim myDateTemp As String
    Dim myDate1 As String
    Dim myDate2 As String
    Dim HGDW_CV1 As String
    Dim HGDW_CV2 As String

    myDateTemp = Format(Date, "yyyy-mm-dd")
    myDate1 = Replace(myDateTemp, "-", "_")
    myDate2 = Format(Date, "yyyymmdd")

    HGDW_CV1 = myDate1 & "_" & myDate2 & "*_GDW_Audit_CView_Report.txt*"
    HGDW_CV2 = "35999_HR_Global_Data_Warehouse_CView_PROD_" & myDate2 & ".txt"

    Name "C:\Users\bf91955\SourceFldr\" & HGDW_CV1 As _ 
    "C:\Users\bf91955\SourceFldr\" & HGDW_CV2

End Sub

我不确定这是否是您的意思,但您可以使用带有通配符的 Dir 函数来尝试获取文件名。

假设我有一个名为

的文件

2018_02_28_20180228_XXXXXX_GDW_Audit_CView_Report.txt

我可以按如下方式检索实际名称。第一场比赛。如果没有找到,则没有真正的错误处理,只是测试该字符串是否被分配了一个不同于它初始化的值。您可以将文件夹路径作为变量传递。

Sub TEST()

    Dim fname As String

    fname = Dir("C:\Users\User\Desktop\Test\*_GDW_Audit_CView_Report.txt")

    If fname <> vbNullString Then

        Debug.Print fname

    End If

End Sub

传递文件夹变量和 date1 的示例(注意 date1 = "2018_02_28" 截至目前):

Sub TEST()

    Dim myDate1 As String

    myDate1 = Format$(Date, "yyyy_mm_dd")

    'Debug.Print myDate1

    Dim fname As String
    Dim folderPath As String

    folderPath = "C:\Users\User\Desktop\Test"

    fname = Dir(folderPath & Application.PathSeparator & myDate1 & "*_GDW_Audit_CView_Report.txt")

    If fname <> vbNullString Then

        Debug.Print fname

    End If

End Sub

为什么我使用 Application.PathSeparator ?在尝试添加分隔符之前,您应该真正测试分隔符的存在。在这种情况下,我出于兼容性原因使用它。这将在 Mac 和 Windows 之间使用正确的分隔符。

有关信息,请参见此处:

Excel 2016 电源编程 VBA (2016) 第四部分。开发 Excel 应用程序,第 21 章。了解兼容性问题

引用:

If your code deals with paths and filenames, you need to construct your path with the appropriate path separator (a colon for the Mac, a backslash for Windows). A better approach is to avoid hard-coding the path separator character and use VBA to determine it. The following statement assigns the path separator character to a variable named PathSep:

PathSep = Application.PathSeparator

参考:

http://www.excelfunctions.net/vba-dir-function.html