Excel VBA – 保存为文件时忽略连续的空白行

我在Sheet1有一些内容,我正在做一些操作并将它们写入到Sheet2

目标是将Sheet2写入.txt文件。 范围始终是来自Sheet2 A1:A2320 。 所以我循环并在输出文件中打印它们。

我面对的问题是后处理有一组空行进入输出文件,它总是有2321行(这是我的代码预计)。 在打印之前,我需要删除范围为A1:A2320中的所有后续空行,只有在有多个连续空白的情况下。

例如,如果这是操作后的表格温度

 A B C D E . 

这应该写成

 A B C D E . 

这是我迄今为止所做的

 Private Sub Make_Click() Dim numFields As Integer Dim numRows As Integer Dim curField As Integer Dim curRow As Integer Dim tmpText As String Dim outputFile As Variant numFields = 1 numRows = 2320 curField = 1 curRow = 1 outputFile = Application.GetSaveAsFilename(InitialFileName:=ActiveWorkbook.Path _ & "\", filefilter:="Text Files (*.txt), *.txt", _ Title:="Output file name (will overwrite)") If outputFile = False Then Exit Sub End If On Error GoTo failed Open outputFile For Output As #1 For curRow = 1 To numRows For curField = 1 To numFields tmpText = ActiveWorkbook.Sheets("Temp").Cells(curRow, curField).Value Print #1, tmpText; If curField < numFields Then Print #1, vbTab; End If Next curField Print #1, vbLf; Next curRow Close #1 MsgBox "File " & outputFile & " written. " & numFields & " fields, " & numRows & " rows." Exit Sub failed: On Error Resume Next Close #1 MsgBox "Couldn't create/overwrite file." End Sub 

如果你只处理一列数据,那么检查空白是微不足道的。 如果你总是只处理A列,那你为什么要穿过列? 你可以使用一个计数器来跟踪你连续有多less空行

 Dim counter As Integer counter = 0 ... For curRow = 1 To numRows tmpText = ActiveWorkbook.Sheets("Temp").Cells(curRow, 1).Value If Len(tmpText) > 0 Then If counter = 1 Then Print #1, vbLf End If Print #1, tmpText Print #1, vbLf counter = 0 Else counter = counter + 1 End If Next curRow 

我们只是延迟打印单个空白行,直到find下一个非空白行。 现在,如果您想在最后一行保留一个空格,则需要在该代码的末尾添加一个if语句。