【问题标题】:Removing White Space删除空白
【发布时间】:2016-03-11 15:22:03
【问题描述】:

我需要帮助从名为“工作表”的 Excel 电子表格中的每一行创建单独的文本文件。我希望文本文件以A列+“结果”+H列的内容命名(应该隐藏在.txt文件中,以B-G列为内容,我已经完成了编码。请找到以下内容。但是我在 .txt 输出文件中收到了空格。请找到屏幕截图。我无法修剪这个空格。

我将如何进一步解决问题?

提前致谢。

VBA 代码:

Sub WriteTotxt()

Const forReading = 1, forAppending = 3, fsoForWriting = 2
Dim fs, objTextStream, sText As String
Dim lLastRow As Long, lRowLoop As Long, lLastCol As Long, lColLoop As Long

lLastRow = Cells(Rows.Count, 1).End(xlUp).Row

For lRowLoop = 1 To lLastRow

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set objTextStream = fs.opentextfile("D:\EXCEL_TXT_TEST\New folder\" & Cells(lRowLoop, 8) & "-" & "RESULT" & "-" & Cells(lRowLoop, 1) & ".txt", fsoForWriting, True)

    sText = ""
    sText1 = ""

    For lColLoop = 1 To 7
    If lColLoop <> 7 Then

        sText = sText & "<" & Cells(lColLoop) & ">" & "," & Chr(0)
        sText1 = sText1 & Cells(lRowLoop, lColLoop) & "," & Chr(0)

     Else

      sText = sText & "<" & Cells(lColLoop) & ">" & Chr(0)
      sText1 = sText1 & Cells(lRowLoop, lColLoop) & Chr(0)

      End If


    Next lColLoop

    objTextStream.writeline (Left(sText, Len(Trim(sText)) - 1))
    objTextStream.writeline (Left(sText1, Len(Trim(sText1)) - 1))


    objTextStream.Close
    Set objTextStream = Nothing
    Set fs = Nothing

Next lRowLoop

End Sub

【问题讨论】:

  • 我认为 TRIM 只适用于 CHR(32) 而不是 CHR(0)。
  • 但是如果我们使用 CHR(32) 而不是 CHR (0) 那么文件内容的最后一个字符将被删除。有什么建议吗?
  • 因为这两行? objTextStream.writeline (Left(sText, Len(Trim(sText)) - 1)) objTextStream.writeline (Left(sText1, Len(Trim(sText1)) - 1))。你在做 left( , Len() - 1)

标签: vba excel whitespace


【解决方案1】:

您可以像这样从字符串中删除所有空行 mystr = replace(mystr, vblf &amp; vbcr, "") 这将删除空行,而不是包含空格或其他您看不到的字符的行..

【讨论】:

    【解决方案2】:

    我也可以帮助您编写代码,但是您是否先尝试过一种简单的方法?

    您为什么不直接文件-->另存为.csv,然后替换您的标题?您的数据输出将非常相似,除了您列出的条目之前的" " 空间。懒惰但容易。

    根据你的模块调整它,你可以像你拥有的所有东西一样擦除......

    ActiveWorkbook.SaveAs Filename:= _
    "c:\MyFile.csv", FileFormat:=xlCSV _
    , CreateBackup:=False
    

    然后,只要把你的数据读回来,字符串操作就很容易了。

    【讨论】:

    • 感谢您的回复。如果您能在我的代码中帮助我,那就太好了,因为对此有一些特定的要求。再次感谢。
    猜你喜欢
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2011-05-01
    • 2015-01-18
    相关资源
    最近更新 更多