简体   繁体   English

VBA搜索文件名的一部分,看看文件是否存在?

[英]vba search part of a file name to see if file exists?

I have several text files (.txt) all called "Log" followed by a date like so (11-2014) and a random number like "34450" 我有几个文本文件(.txt),都称为“日志”,后跟日期(如11-2014)和随机数,如“ 34450”

so my folder directory (P:) looks like: 所以我的文件夹目录(P :)看起来像:

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. 我想做的是使用vba代码对日志文件中包含当天日期的同一月份和年份的所有事件进行计数。

so today's month is 11 and todays year is 2014 所以今天是11月,今天是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. 因此,我想计算文件名“(11-2014)”的日期位与当前日期/今天日期的月份和年份相匹配的所有日志文件。

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 您可以使用Left或InStr函数查找子字符串是否为另一个字符串的一部分

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. 其中logName是在磁盘上找到的文件名, logNameToFind是您要查找的模式。

To get all the files from a directory use Dir function 要从目录中获取所有文件,请使用Dir函数

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. UBound(myArray)进行计数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM