[英]Reading data from multiple text files (EOF, Do-Until)
I want my macros to read certain lines from each text files (saved in a server folder) but so far, I can only get the macros to return the correct values for from the first text file... 我希望宏从每个文本文件(保存在服务器文件夹中)读取某些行,但到目前为止,我只能从第一个文本文件中获取宏以返回正确的值...
I think it's because I don't really understand the 'Open xxx for input as #1' command... here is the macros: 我认为这是因为我不太了解'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
The first sub is to ask users to enter and select how many text files they want to read, and the second sub is suppose to bring back the correct values for each text file. 第一个子项是要求用户输入并选择他们要读取的文本文件的数量,第二个子项是假定为每个文本文件恢复正确的值。
Thanks in advance!!! 提前致谢!!!
You may want to try this: 您可能要尝试以下操作:
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.