该代码不会按原样工作。您有来自函数的代码和来自过程的代码相互交织在一起。
第一行定义你的程序:
Sub LastModifiedFile()
然后你就有了与函数相关的代码。
这段代码应该找出传递给它的每个文件名的最后修改日期,并将该日期返回给主过程......你可以看到倒数第二行,上面写着FileLastModified = s。这是它将值传回调用过程的那一行。
Function FileLastModified(strFullFileName As String)
Dim fs As Object, f As Object, s As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(strFullFileName)
s = UCase(strFullFileName) & vbCrLf
s = s & "Last Modified: " & f.DateLastModified
FileLastModified = s
Set fs = Nothing: Set f = Nothing
接下来,您将再次获得主过程中的一些代码。
您可以在第二行看到它要求 FileLastModified 函数查看您传递给它的任何文件的路径。
这里有一个问题——第一行调用了一个名为FileExists(strFullName) 的函数。这会将文件路径传递给您尚未发布的函数,该函数首先询问文件是否存在 - 它应该返回 TRUE 或 FALSE。
这里的另一个问题是,如果找不到文件,它会说它超过五年,而不是说它根本不存在。
If FileExists(strFullName) Then
MsgBox FileLastModified(strFullName)
Else
MsgBox "File Older than 5 Years : " & vbNewLine & strFullName
End If
在这段代码之后有两行——一行结束函数,另一行结束子。
End Function
End Sub
您的代码应该看起来更像这样:
Sub LastModifiedFile()
'Check if File Exists using `FileExists` function.
If FileExists(strFullName) Then
'If it does exist then pass the path to see when it was last modified.
MsgBox FileLastModified(strFullName)
Else
'If it doesn't exist then say it's older than 5 years.
MsgBox "File Older than 5 Years : " & vbNewLine & strFullName
End If
End Sub
Function FileLastModified(strFullFileName As String)
Dim fs As Object, f As Object, s As String
Set fs = CreateObject("Scripting.FileSystemObject")
'Returns a file object.
Set f = fs.GetFile(strFullFileName)
s = UCase(strFullFileName) & vbCrLf
'f.DateLastModified returns the modified date of the file object.
s = s & "Last Modified: " & f.DateLastModified
'Pass the string variable back to whatever called it.
FileLastModified = s
Set fs = Nothing: Set f = Nothing
End Function
您仍然需要 FileExists 函数的代码。