[英]Reading data from multiple text files (EOF, Do-Until)
我希望宏從每個文本文件(保存在服務器文件夾中)讀取某些行,但到目前為止,我只能從第一個文本文件中獲取宏以返回正確的值...
我認為這是因為我不太了解'Open xxx for input as#1'命令...這是宏:
Public CurrCell As Range
Public noLines As Integer
Sub NextCell()
Dim myFile As String
noLines = InputBox("Enter the number of TRs to add")
Range("A1").Activate
For Each CurrCell In Range(Cells(2, 1), Cells(noLines + 1, 1))
myFile = Application.GetOpenFilename()
ActiveCell.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = myFile
Next CurrCell
End Sub
Sub GrabData()
Dim myFileName As String
Dim text As String
Dim textline As String
Dim Incidental As Integer
Dim TotalAccom As Integer
Dim Incidental_value As String
Dim TotalAccom_value As String
Dim i As Integer
For i = 1 To noLines
myFileName = Cells(i + 1, 1)
Open myFileName For Input As #1
Do Until EOF(1)
Line Input #1, textline
text = text & textline
Loop
Close #1
Incidental = InStr(text, "INCIDENTAL ALLOWANCE")
Cells(i + 1, 2).Value = Mid(text, Incidental + 22, 5)
Next i
End Sub
第一個子項是要求用戶輸入並選擇他們要讀取的文本文件的數量,第二個子項是假定為每個文本文件恢復正確的值。
提前致謝!!!
您可能要嘗試以下操作:
Public noLines As Long ' Use Public if this is to be accessed by another Module
Sub NextCell()
Dim i As Long, oRng As Range
noLines = CLng(InputBox("Enter the number of TRs to add"))
' First store all the filenames, store them below A1
Set oRng = Range("A1")
For i = 1 To noLines
oRng.Offset(i, 0).Value = Application.GetOpenFilename()
Next
Set oRng = Nothing
' Then invoke the sub "GrabData"
GrabData
End Sub
Sub GrabData()
Const sMarker = "INCIDENTAL ALLOWANCE"
Dim i As Long, oRng As Range
'Dim myFileName As String
Dim text As String
Dim textline As String
Dim Incidental As Long
'Dim TotalAccom As Integer
'Dim Incidental_value As String
'Dim TotalAccom_value As String
Set oRng = Range("A1")
For i = 1 To noLines
text = "" ' Reset the text to blank!
' Now go through the list of filenames stored below A1
Open oRng.Offset(i, 0).Value For Input As #1
Do Until EOF(1)
Line Input #1, textline
text = text & textline
Loop
Close #1
' Get location of text after sMarker
Incidental = InStr(text, sMarker) + Len(sMarker) + 2
' Store 5 characters of text after sMarker to column C
oRng.Offset(i, 2).Value = Mid(text, Incidental, 5)
Next i
Set oRng = Nothing
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.