使用VBA从文本文件中删除空行

时间:2017-07-11 14:55:14

标签: excel vba excel-vba

这是我之前提出的问题的继续。我迫切希望找到一种方法,从目前为止我没有成功的excel文件生成时从文本文件中删除尾随空白行。我刚才找到了下面的代码,当我执行它时,我可以看到它有我想要的基础(我认为),但我没有修改它的技能,所以忽略任何包含数据的行并删除空格。任何人都可以帮我修改它,以便它可以删除那些讨厌的白色空间吗?

 Sub AltText()
  Dim File As String
  Dim VecFile() As String, Aux As String
  Dim i As Long, j As Long
  Dim SizeNewFile As Long

  File = Application.GetOpenFilename

  'Import file lines to array excluding first 3 lines and
  'lines starting with "-"
  Open File For Input As 1
  i = 0
  j = 0
  Do Until EOF(1)
    j = j + 1
    Line Input #1, Aux
    If j > 3 And InStr(1, Aux, "-") <> 1 Then
        i = i + 1
        ReDim Preserve VecFile(1 To i)
        VecFile(i) = Aux
    End If
  Loop
  Close #1
  SizeNewFile = i

  'Write array to file
  Open File For Output As 1
  For i = 1 To SizeNewFile
    Print #1, VecFile(i)
  Next i
  Close #1

  MsgBox "File alteration completed!"

 End Sub

2 个答案:

答案 0 :(得分:2)

要删除空白行,请尝试以下代码:

Sub AltText()
   Dim inFile As String
   Dim outFile As String
   Dim data As String

   inFile = Application.GetOpenFilename
   Open inFile For Input As #1

   outFile = inFile & ".alt"
   Open outFile For Output As #2

   Do Until EOF(1)
      Line Input #1, data

      If Trim(data) <> "" Then
         Print #2, data
      End If
   Loop

   Close #1
   Close #2

   Kill inFile
   Name outFile As inFile

   MsgBox "File alteration completed!"
End Sub

答案 1 :(得分:1)

您需要查找空格和回车符,因此在阅读完行后,请检查内容:

dim temp as string

temp = Replace (aux, chr(10), "")  
temp = Replace (temp,chr(13),"")
temp = Rtrim(Ltrim(temp))  ' remove just blank stuff

现在检查长度:

if j > 3 and Len(temp) <> 0 then
    ......
    add the lines

因此您的代码应如下所示:

Sub AltText()
  Dim File As String
  Dim VecFile() As String, Aux As String
  Dim i As Long, j As Long
  Dim SizeNewFile As Long

  File = Application.GetOpenFilename

  'Import file lines to array excluding first 3 lines and
  'lines starting with "-"
  Open File For Input As 1
  i = 0
  j = 0
  Do Until EOF(1)
    j = j + 1
    Line Input #1, Aux

    '=====
     dim temp as string

     temp = Replace (aux, chr(10), "")  
     temp = Replace (temp,chr(13),"")
     temp = Rtrim(Ltrim(temp))  ' remove just blank stuff
    '======

    If j > 3 And Len(temp) <> 0 Then
        i = i + 1
        ReDim Preserve VecFile(1 To i)
        VecFile(i) = Aux
    End If
  Loop
  Close #1
  SizeNewFile = i

  'Write array to file
  Open File For Output As 1
  For i = 1 To SizeNewFile
    Print #1, VecFile(i)
  Next i
  Close #1

  MsgBox "File alteration completed!"

 End Sub