使用 VBA 创建 .CSV 文件时消除空白行和列

时间:2021-05-14 15:42:34

标签: python excel vba csv

我正在尝试将要在 python 中使用的文件输出为 csv。

但是,当我运行 VBA 宏时,保存的 csv 文件包含空白行和列的逗号。因为我不能使用python中的文件来读取和做其他工作。

我在这里使用了另存为 csv 文件的脚本:

Sub FromExcelToNpad()

For m = 1 To 24
    ThisWorkbook.Sheets("ColumnOpenSeesInput-0- I").Cells(1, m) = i
    i = i + 1
Next m

    Dim myCSVFileName As String
    Dim tempWB As Workbook

    Application.DisplayAlerts = False
    On Error GoTo err

    myCSVFileName = ThisWorkbook.Path & "\" & "Column_0_I.csv"

    ThisWorkbook.Sheets("ColumnOpenSeesInput-0- I").Activate
    ActiveSheet.Copy
    Set tempWB = ActiveWorkbook

    With tempWB
    .SaveAs Filename:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
    .Close
    End With
err:
    Application.DisplayAlerts = True
End Sub

当我运行它时,我的输出文件看起来像;

enter image description here

如何消除空白行和列我没有找到好的方法。我只想用这种方式保存有用的单元格。

2 个答案:

答案 0 :(得分:0)

我不使用 Windows,因此无法在 VBA 中检查如何执行此操作,但我会使用 Pythonpandas 删除空行和列。

df = df.dropna(how='all', axis=0)  # remove rows with NaN in all cells
df = df.dropna(how='all', axis=1)  # remove cols with NaN in all cells

最小的工作示例。

我仅使用 io.StringIO 来模拟带有数据的文件。你应该用 filename

测试它
text = '''A,B,C,,,,,,,,,,,
1,2,3,,,,,,,,,,,
4,5,6,,,,,,,,,,,
,,,,,,,,,,,,,
,,,,,,,,,,,,,
,,,,,,,,,,,,,
,,,,,,,,,,,,,
'''

import pandas as pd
import io

df = pd.read_csv(io.StringIO(text))
#df = pd.read_csv("data.csv")

df = df.dropna(how='all', axis=0)  # remove rows with NaN in all cells
df = df.dropna(how='all', axis=1)  # remove cols with NaN in all cells

print( df )

结果:

     A    B    C
0  1.0  2.0  3.0
1  4.0  5.0  6.0

答案 1 :(得分:0)

试试这个代码:

' deletes blank rows on the specified  worksheet.
' If the argument is omitted, ActiveSheet is processed
Public Sub DelEmptyRows(Optional ws As Worksheet = Nothing)
    Dim toDel As Range, rng As Range, r As Range
    
    If ws Is Nothing Then Set ws = ActiveSheet
    
    Set rng = ws.Range(ws.Cells(1, 1), ws.UsedRange)
    For Each r In rng.Rows
        If WorksheetFunction.CountA(r) = 0 Then
            If toDel Is Nothing Then
                Set toDel = r
            Else
                Set toDel = Union(toDel, r)
            End If
        End If
    Next
    If Not toDel Is Nothing Then toDel.EntireRow.Delete
End Sub

' deletes blank columns on the specified  worksheet.
' If the argument is omitted, ActiveSheet is processed
Public Sub DelEmptyCols(Optional ws As Worksheet = Nothing)
    Dim toDel As Range, rng As Range, c As Range
    
    If ws Is Nothing Then Set ws = ActiveSheet
    
    Set rng = ws.Range(ws.Cells(1, 1), ws.UsedRange)
    For Each c In rng.Columns
        If WorksheetFunction.CountA(c) = 0 Then
            If toDel Is Nothing Then
                Set toDel = c
            Else
                Set toDel = Union(toDel, c)
            End If
        End If
    Next
    If Not toDel Is Nothing Then toDel.EntireColumn.Delete
End Sub