I have several text files (.txt) all called "Log" followed by a date like so (11-2014) and a random number like "34450"
so my folder directory (P:) looks like:
Log (11-2014) 12234.txt
Log (10-2014) 45546.txt
Log (08-2014) 686868.txt
Log (11-2014) 343434.txt
what I want to do is use vba code to count all occurrences where the log files contain the same month and year of todays date.
so today's month is 11 and todays year is 2014
so I want to count all log files where the date bit of the file name "(11-2014)" matches the month and year of the current date/today's date.
here's what I've tried but it doesn't work, I keep getting "found" even when the file doesn't exist, please could someone show me what im doing wrong?
Dim iMonth As Integer
Dim iYear As Integer
Dim target As String
iMonth = Month(Date)
iYear = Year(Date)
thefile = "P:\Log *(" & iMonth & "-" & iYear & ")"
If thefile > 0 Then
MsgBox "Found"
Else
MsgBox "Not"
End If
you can use Left or InStr function to find if a substring is part of another string
dim logName as string, logNameToFind as string
if Left(logName, Len(logNameTofind)) = LogNameToFind then
MsgBox "Found"
end if
or
dim logName as string, logNameToFind as string
if InStr(logName, logNameToFind) = 1 then
MsgBox "Found"
End if
where logName is the file name found on disk and logNameToFind is the pattern you are looking for.
To get all the files from a directory use Dir function
You can use the below function to fill an array with all the files matching your pattern, then use
UBound(myArray)
to get a count.
Private Function GetFileList(FileSpec As String) As Variant
' Returns an array of filenames that match FileSpec
' If no matching files are found, it returns False
Dim FileArray() As Variant
Dim FileCount As Integer
Dim FileName As String
On Error GoTo NoFilesFound
FileCount = 0
FileName = Dir(FileSpec)
If FileName = "" Then GoTo NoFilesFound
'Loop until no more matching files are found
Do While FileName <> ""
FileCount = FileCount + 1
ReDim Preserve FileArray(1 To FileCount)
FileArray(FileCount) = FileName
FileName = Dir()
Loop
GetFileList = FileArray
Exit Function
NoFilesFound:
GetFileList = False
End Function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.