我正在使用下面的宏将选定范围(在Excel中)写入.txt文件。
Sub ExportTXT()
Dim myFile As String
Dim rng As Range
Dim cellValue As Variant
Dim i As Integer
Dim j As Integer
myFile = Application.DefaultFilePath & "\sales.txt"
Set rng = Range(Cells(1, 1), Cells(10, 4))
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
cellValue = rng.Cells(i, j).Value
If j = rng.Columns.Count Then
Write #1, cellValue
Else
Write #1, cellValue,
End If
Next j
Next i
Close #1
End Sub
如何跳过空白行?
我尝试使用 Isempty(cellValue)= True **和空字符串**“” 条件语句。
关于如何检查cellValue内容以查看其是否为空并仅写有数据行的任何想法。
答案 0 :(得分:2)
我对您的代码做了一些更改
Sub ExportTXT()
Const DELIMITER = ","
Dim myFile As String
Dim rng As Range
Dim cellValue As Variant
Dim i As Integer
Dim j As Integer
Dim sngRow As Range
Dim vDat As Variant
myFile = Application.DefaultFilePath & "\sales.txt"
With ActiveSheet
Set rng = .Range(.Cells(1, 1), .Cells(10, 4))
End With
Dim noCol As Long
noCol = rng.Columns.Count
Open myFile For Output As #1
For Each sngRow In rng.Rows
vDat = WorksheetFunction.Transpose(WorksheetFunction.Transpose(sngRow))
vDat = Join(vDat, DELIMITER)
If Len(vDat) >= noCol Then
Write #1, vDat
End If
Next
Close #1
End Sub
更新基于其中一项评论,请使用以下声明以避免“文字限定”
Print #1, vDat
代替
Write #1, vDat