因此,我有一个代码,提示用户在其计算机上查找特定文件。这些文件的命名方式始终为“ 每日运营报告-年月日”。 我需要确保用户选择的文件具有与今天相同的日期。我知道如何比较两个日期并找出它们是否相等。但是,我不知道如何让excel在字符串中查找数字。
'Previous code not relevant to the question
Dim strFilePath, fName As String
Dim wdDoc As Object
strFilePath = Application.GetOpenFilename
If strFilePath = "False" Then End 'Pressed cancel
fName = strFilePath
Set wdDoc = GetObject(fName)
执行上述代码后,我可以在(wdDoc)中找到文件的名称,例如:
MsgBox wdDoc
我得到以下结果:
每日运营报告-2019年12月21日
如何将文件与今天的日期进行比较?我相信比较天数比比较两个日期的天数,月数和年数更容易和更快?
对不起,如果我没有任何道理,那么我只是想一会儿。
感谢您的帮助。
答案 0 :(得分:1)
有很多方法可以做到这一点,但这是其中一种。它使用文件名并将其转换为日期。您可以在该日期做些什么来进行比较。
Function GetDateFromFilename(sFilename As String) As Date
Dim sFullDate As String
Dim sDay As String
Dim sNum As String
Dim nDig As Integer: nDig = 1
' get rid of the extension just in case it exists
sFilename = Split(sFilename, ".")(0)
' get just the date part for processing
If Instr(sFilename, " - ") = 0 Then
Msgbox "Filename not in proper format"
GetDateFromFilename = CDate("1/1/1990")
Exit Function
End If
sFullDate = Split(sFilename, " - ")(1)
' get the first digit of that
sNum = Left$(sFullDate, nDig)
' loop thru the characters until there is an alpha character
Do While nDig <= Len(sFullDate)
If IsNumeric(sNum) Then
sDay = sDay & sNum
Else
' found the first alpha, so we are done here
Exit Do
End If
' check the next character
nDig = nDig + 1
sNum = Mid$(sFullDate, nDig, 1)
Loop
' build a string that correctly resembles a date (month first)
sFullDate = Split(sFullDate)(1) & " " & sDay & " " & Split(sFullDate)(2)
' or build a string that correctly resembles a date (day first)
' sFullDate = sDay & " " & Split(sFullDate)(1) & " " & Split(sFullDate)(2)
' convert it to an actual date and return it
GetDateFromFilename = CDate(sFullDate)
End Function
用法:
Dim dtFileDate As Date
dtFileDate = GetDateFromFilename("Daily Operations Report - 21st December 2019")
' show just the day number
MsgBox Format$(dtFileDate, "d")
注意::如果文件名字符串的格式不正确,则很有可能会出错,但是您的问题暗示它将始终