【问题标题】:Removing unwanted rows while importing text files and delimiting the data在导入文本文件和分隔数据时删除不需要的行
【发布时间】:2014-07-16 12:15:08
【问题描述】:

我有一个代码,可以将记事本数据导入到 excel 中,向其中添加文件名的新列。现在的挑战是,在记事本中,数据的开头和结尾都有不需要的行。

  1. 如何删除它?
  2. 我们通常对数据进行分隔,在将文件导入 Excel 时不会发生这种情况。

记事本前五行如下

驱动器 Y 中的卷没有标签。 卷序列号为 3000-0003

Y的目录:\

最后两行如下

          0 File(s)              0 bytes
        1796 Dir(s)  2,497,977,561,088 bytes free

数据是这样的 2013 年 12 月 19 日下午 5:27 用户 1

使用当前代码,我得到这样的输出

第 1 列 = Abc_notepad1.text(文本文件名)第 2 列 = 2013 年 12 月 19 日下午 5:27 用户 1

我希望代码删除前 5 行和后 2 行 和这样的输出 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

【问题讨论】:

  • 数据如下 Column1 Column 2 Text - 1.txt 05/20/2013 10:41 AM User
  • 给你的示例数据如下:Column1 = ".." Column2 = ".." etc.
  • 更新了主要问题本身的字段

标签: excel vba


【解决方案1】:

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)

【讨论】:

  • 非常感谢..为您提供帮助
  • 您好,我在医疗急救中..所以我无法执行此操作..我可以知道在哪里更新此代码吗?
  • 答案 1 在Do While myFile &lt;&gt; "" 前面。答案 2 在strRecord = myFile &amp; delim &amp; strRecord 之后。我认为答案 3 在 strRecord = myFile &amp; delim &amp; strRecord 之后,在 Data is like this 12/19/2013 05:27 PM User1 的某个地方。如果这回答了您的问题,请接受。
猜你喜欢
  • 1970-01-01
  • 2011-01-17
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-03
  • 1970-01-01
相关资源
最近更新 更多