![](/img/trans.png)
[英]Search all columns in an excel column and check value against file name in folder to see if exists?
[英]vba search part of a file name to see if file exists?
我有幾個文本文件(.txt),都稱為“日志”,后跟日期(如11-2014)和隨機數,如“ 34450”
所以我的文件夾目錄(P :)看起來像:
Log (11-2014) 12234.txt
Log (10-2014) 45546.txt
Log (08-2014) 686868.txt
Log (11-2014) 343434.txt
我想做的是使用vba代碼對日志文件中包含當天日期的同一月份和年份的所有事件進行計數。
所以今天是11月,今天是2014年
因此,我想計算文件名“(11-2014)”的日期位與當前日期/今天日期的月份和年份相匹配的所有日志文件。
這是我嘗試過的方法,但是它不起作用,即使文件不存在,我也會不斷“找到”,請有人告訴我我做錯了什么嗎?
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
您可以使用Left或InStr函數查找子字符串是否為另一個字符串的一部分
dim logName as string, logNameToFind as string
if Left(logName, Len(logNameTofind)) = LogNameToFind then
MsgBox "Found"
end if
要么
dim logName as string, logNameToFind as string
if InStr(logName, logNameToFind) = 1 then
MsgBox "Found"
End if
其中logName是在磁盤上找到的文件名, logNameToFind是您要查找的模式。
要從目錄中獲取所有文件,請使用Dir函數
您可以使用下面的函數用與模式匹配的所有文件填充數組,然后使用
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.