我的代码未获取文件夹中的最新文件

时间:2019-01-04 20:47:49

标签: excel vba excel-vba

问题很简单。未获取最新文件。而且这个问题只是由于新年而蔓延。去年一切正常

以下是相关代码:

 Dim yr As String
 Dim mo As String
 Dim destinationsfn As String
 Dim destinationtsfn
 Dim bdate As String
 Dim fdate As String
 Dim destinationfp As String
 Dim destinationfo As String
 Dim destinationShVar As Worksheet
 Dim destinationTorc As Workbook

 Dim sht As Worksheet

 yr = Format(Date, "yyyy")
 mo = Format(Date, "mm")  

 If mo < 10 Then
 mo = Right(mo, 1)
 End If


 destinationfo = Dir("W:\Product Platforms\Macro\New destination Database\destination Master File\" & yr & "\" & mo & "*", vbDirectory)
 destinationfo = Trim(destinationfo)

 destinationfp = "W:\Product Platforms\Macro\New destination Database\destination Master File\" & yr & "\" & destinationfo & "\"

 destinationsfn = Dir(destinationfp & "*-*.xlsx")

Do While Len(destinationsfn) > 0
fdate = FileDateTime(destinationfp & destinationsfn)
    If fdate > bdate Then
        destinationtsfn = destinationsfn
        bdate = fdate
    End If
    destinationsfn = Dir
Loop   

 On Error Resume Next
 Workbooks.Open (destinationfp & destinationtsfn)

1 个答案:

答案 0 :(得分:2)

fdatebdate都声明为字符串。

因此,在这一行:

If fdate > bdate Then

您没有将日期与>运算符进行比较。您正在比较字符串,这意味着要考虑字母顺序。

如果您在美国或日期格式为"MM/DD/YYY..."的任何国家中,并且您在Excel中的区域设置反映了这一点,则字符串"12/31/2018"的计算结果将大于字符串{{1} },由于字母顺序。如果它们是日期,则相反。

最简单的解决方法可能只是将"01/01/2019"bdate声明为变量或日期。