我在Sheet1
中有一些内容,我正在做一些操作并在Sheet2
中编写它们。
目标是将Sheet2
写入.txt
文件。范围始终为A1:A2320
Sheet2
。所以我在输出文件中循环并打印它们。
我面临的问题是操作后操作有一组空白行进入输出文件,它总是有2321行(根据我的代码,这是预期的)。我需要在打印前删除A1:A2320
范围内的所有后续空白行,仅当有多个连续空白时才会删除。
例如,如果这是操作后的表单Temp
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
答案 0 :(得分:1)
如果您只处理一列数据,那么检查空白是微不足道的。如果你总是只处理A列,为什么要单步执行列?您可以使用计数器来跟踪连续多少空白行......
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
我们只是延迟打印单个空白行,直到找到下一个非空白行。现在,如果你想在最后一行出现一个空格,你需要在这段代码的末尾加上一个if语句。