【发布时间】:2016-03-27 04:10:57
【问题描述】:
我正在编写代码以将数据从 Excel 文件转换为 CSV 文件。但在转换为 CSV 文件之前,我想遍历数据以删除任何空行。转换后代码会在记事本中打开供用户查看。我意识到,只要任何单元格中有格式,它就会被视为空白单元格。
在下面显示的屏幕截图中,我更改了 3 行(第 14、15 和 16 行)的格式。 After adding and deleting of the rows, these are blank fields.
转换后,我意识到有 3 行看起来像“,,,,”。 Extra 3 lines at the bottom
我尝试删除格式,但无法删除字体等格式。我可以这样做的唯一方法是删除带有格式的额外空白行。
在下面的 VBA 代码中,我设法检测到字段包含空格的列,但我似乎无法删除这些行。我认为这是格式问题并使用了 .ClearFormats 和 .ClearContents,但它们也不起作用。我不确定我还能如何删除这些行。
但是,我很肯定任何单元格中任何形式的格式更改都会导致多余的行。任何帮助将不胜感激。
我当前的代码:
Option Explicit
Sub CreateCSV()
'Declare the data type of the variables
Dim wks As Worksheet
Dim lastCol As Integer
Dim lastRow As Long
Dim iCol As Integer
Dim iRow As Long
Dim sFilename As String
Dim cellValue As String
Dim MyTextFile
'Dim previous As Dataset
'Set the Wkb to the current active workbook and set Wks to the current sheet opened
Set wks = ActiveWorkbook.ActiveSheet
'Set the location of the csv file to a variable
sFilename = "C:\Users\Public\Desktop\cp_resi_nostro.csv"
'Set the column and row number of last cell that is not empty to a variable
lastCol = wks.Cells.SpecialCells(xlCellTypeLastCell).Column
lastRow = wks.Cells.SpecialCells(xlCellTypeLastCell).Row
'Check through each cell to identify any empty cells
For iRow = 1 To lastRow
For iCol = 1 To lastCol
cellValue = wks.Cells(iRow, iCol).Value
Next iCol
'If Trim(cellValue) = "" Then
'Rows(iRow).Delete
'wks.AcceptChanges()
'End If
Next iRow
'Save as .CSV file and in a specific folder stated
wks.SaveAs Filename:=sFilename, FileFormat:=xlCSV
Application.DisplayAlerts = True
'Notify users that the .CSV file has been saved
MsgBox sFilename & " saved"
'To ask Ash which format he wants
MyTextFile = Shell("C:\Windows\notepad.exe C:\Users\Public\Desktop\cp_resi_nostro.csv", vbNormalFocus)
'Set Wkb and Wks to its default value
Set wks = Nothing
End Sub
【问题讨论】:
标签: vba excel export-to-csv