【问题标题】:Eliminate Blank Rows and Columns When Creating .CSV File with VBA使用 VBA 创建 .CSV 文件时消除空白行和列
【发布时间】:2021-05-14 15:42:34
【问题描述】:

我正在尝试将要在 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

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

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

【问题讨论】:

  • 你在SaveAs的官方文档中发现了什么?
  • 使用谷歌vba excel saveas skip empty cells我发现how not to skip empty first cell when saving as .CSV?
  • 尝试使用 pandas 包将您的 csv 读入数据帧
  • @furas 我有一些来自 excel 计算的其他变量的输入。然后我准备所有输入以在 python 中作为 csv 格式使用。但是,vba 并没有像我想的那样工作。在保存之前我没有找到正确的命令来删除空单元格。我也会检查你提到的链接!谢谢!

标签: python excel vba csv


【解决方案1】:

我不使用 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

【讨论】:

    【解决方案2】:

    试试这个代码:

    ' 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
    

    【讨论】:

      猜你喜欢
      • 2018-03-24
      • 2020-10-07
      • 2016-05-12
      • 2016-12-26
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多