Excel VBA:macros只导出非空白单元格

今天是个好日子,

我有这个macros,导出所有公式的单元格,但空白输出。

我只希望显示为非空白的单元格导出。 有任何想法吗?

Sub Export_A() Dim sPath As String Dim SFile As String Dim nLog As Integer sPath = "C:\AAAWork\" SFile = sPath & ActiveSheet.Range("P9") & ".txt" nfile = FreeFile Open SFile For Output As #nfile For i = 1 To ActiveSheet.UsedRange.Rows.Count Set ThisCell = ActiveSheet.Range("A" & i) If ThisCell.Text <> "" Then ' sInDate = ThisCell.Text 'sOutDate = Format(ThisCell.Value, "mm/yyyy") sOutDate = Format(ThisCell.Value, "yyyy-mm") 'stemp = """" & sOutDate & """" this gives the date the " in the beginning and end stemp = "" & sOutDate & "" For j = 1 To 10 If j = 1 Or j = 2 Or j = 9 Then stemp = stemp & ";" & ThisCell.Offset(0, j) Else 'stemp = stemp & "," & """" & ThisCell.Offset(0, j) & """" This gives every value a " beginning and end stemp = stemp & ";" & ThisCell.Offset(0, j) End If Next End If Print #nfile, stemp Next Close #nfile MsgBox ("Completed a file called " & SFile & " has been generated") End Sub 

这是一个导出到CSV的有趣的方式,但是它被inheritance,并且一切都很好。

尝试将写入行放在For循环的末尾

 Sub Export_A() Dim sPath As String Dim SFile As String Dim nLog As Integer sPath = "C:\AAAWork\" SFile = sPath & ActiveSheet.Range("P9") & ".txt" nfile = FreeFile Open SFile For Output As #nfile For i = 1 To ActiveSheet.UsedRange.Rows.Count Set ThisCell = ActiveSheet.Range("A" & i) If ThisCell.Text <> "" Then ' sInDate = ThisCell.Text 'sOutDate = Format(ThisCell.Value, "mm/yyyy") sOutDate = Format(ThisCell.Value, "yyyy-mm") 'stemp = """" & sOutDate & """" this gives the date the " in the beginning and end stemp = "" & sOutDate & "" For j = 1 To 10 stemp = stemp & ";" & ThisCell.Offset(0, j) Next Print #nfile, stemp End If Next Close #nfile MsgBox ("Completed a file called " & SFile & " has been generated") End Sub 

首先你不需要这个if语句,因为如果输出是真的或者是假的,输出是相同的

  If j = 1 Or j = 2 Or j = 9 Then stemp = stemp & ";" & ThisCell.Offset(0, j) Else 'stemp = stemp & "," & """" & ThisCell.Offset(0, j) & """" This gives every value a " beginning and end stemp = stemp & ";" & ThisCell.Offset(0, j) End If 

如果空格在以下列中,则可以更改为以下代码:

  If ThisCell.Offset(0, j) <> "" Then stemp = stemp & ";" & ThisCell.Offset(0, j) End If 

这将跳过空白列