![](/img/trans.png)
[英]Find “string” in Text File - Add it to Excel File Using Python
[英]Find a string into a text file, read a registration and write in a excel, using vba
在一個文件夾中,我有很多文本文件,擴展名為“date.log”。 每個文件都包含來自各種來源的信息,這些信息由 ID 標識。 這些文件實際上是 csv 文件,帶有“|” 分隔符(豎線/豎線) 我想在每個文件中找到特定 ID 的注冊並將特定行上傳到 excel,(從每個文件中指定行)。 我怎么能用 vba 做到這一點。 文件的格式為:yyyy-mm-dd.log ID 的格式為“PMnnnn”(其中 n 是數字)在每個文件中,ID 可以出現大約 3 次 ID 不在行/注冊的開頭,但是一旦找到注冊,整行必須寫在excel表中。 請為此目的幫助我提供代碼。 感謝所有提出想法的人。
Sub SearchTextFile()
Dim strFileName As String
Dim strSearch As String
Dim StartDate As Date
Dim EndDate As Date
Dim Result() As String
Dim WordCount As Integer
Dim strLine As String
Dim f As Integer
Dim lngLine As Long
Dim myPath As String
f = FreeFile
StartDate = Range("N1")
EndDate = Range("N2")
strSearch = Range("H1")
i = 1
endrow = Cells(Rows.Count, 2).End(xlUp).Row + 1
Range("A6:AE" & endrow).ClearContents
myPath = Application.ActiveWorkbook.Path
For Datafile = EndDate To StartDate Step -1 ' last day in first row
Datafile = Format(Datafile, "dd.mm.yyyy")
Zi = Format(Day(Datafile), "0#")
Luna = Format(Month(Datafile), "0#")
An = Year(Datafile)
filename = "Cnx" & An & "-" & Luna & "-" & Zi & ".log"
strFileName = myPath & "\" & filename
nr_linii = readnrline(strFileName)
Open strFileName For Input As #f
For lngLine = 1 To nr_linii
Line Input #f, strLine
If InStr(1, strLine, strSearch, vbBinaryCompare) > 0 Then
Cells(5 + i, 1) = lngLine
Result() = Split(strLine, "|")
WordCount = UBound(Result())
For j = 2 To WordCount
Cells(5 + i, j) = Result(j)
Next j
i = i + 1
End If
Next lngLine
Close #f
Next Datafile
End Sub
Function readnrline(filename As String) As Integer
Open filename For Input As #1
Do While Not EOF(1)
Line Input #1, sLineOfText
readnrline = readnrline + 1
Loop
Close
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.