我有一个代码,用于将记事本数据导入到Excel中,为其添加新的文件名列。现在的挑战是,在记事本中,数据的开头和结尾都有不需要的行。
记事本前五行如下
驱动器Y中的卷没有标签。 卷序列号为3000-0003
目录Y:\
最后两行如下
0 File(s) 0 bytes
1796 Dir(s) 2,497,977,561,088 bytes free
数据是这样的 12/19/2013 05:27 PM User1
使用当前的Code我可以像这样获得输出
Colum 1 = Abc_notepad1.text(textfile name)Column2 = 12/19/2013 05:27 PM User1
我希望代码删除前五行和后两行 和这样的输出 Column1 = ABC(文本文件名的前3个字母),Column2 = 12/19/2013 05:27 PM,Column3 =,Column4 = User1
Option Explicit
Const myPath = "D:\My Data\"
Const delim = vbTab
Sub MergeMultipleTextFiles()
Dim myFile As String 'filename
Dim strRecord As String 'record string
Dim arrRecord() 'record array
Dim fNum As Integer 'free file number
Dim RowCounter As Long 'row counter
Dim i As Long 'loop variable
On Error GoTo errHandler
myFile = Dir(myPath & "*.txt")
RowCounter = 0
Do While myFile <> ""
fNum = FreeFile
Open myPath & myFile For Input As #fNum
Do While Not EOF(fNum)
'read in the row into the record variable
Line Input #fNum, strRecord
'add the filename to the record variable
strRecord = myFile & delim & strRecord
RowCounter = RowCounter + 1
'resize the record array
ReDim Preserve arrRecord(1 To RowCounter)
arrRecord(RowCounter) = Split(strRecord, delim)
Loop
Close #fNum
'get the next file in the directory
myFile = Dir()
Loop
With ThisWorkbook.Sheets("Sheet1").Range("A1")
For i = 1 To RowCounter
.Offset(i - 1).Resize(, UBound(arrRecord(i)) + 1).Value = arrRecord(i)
Next i
End With
errExit:
'close all open text files
Reset
Exit Sub
errHandler:
'error message goes here
Resume errExit
End Sub
答案 0 :(得分:0)
Q1 - 绕过前5行:
For i1 = 1 to 5
Line Input #fNum, strRecord
Next i1
Q2 - 绕过最后2行:
If InStr(1, strRecord, "File(s)" > 0 then exit Do
Q3 - 获取专栏:
Column1 = Left$(textfilename, 3)
Column2 = Left$(data, 19)
Column3 = ""
Column4 = mid$(data, 21)