简体   繁体   中英

Eliminate Blank Rows and Columns When Creating .CSV File with VBA

I am trying to output file to use in python as csv.

However, when I run my VBA macro, csv file that saved contain commas for blank rows and columns. Becaue of that I can not use the file in python to read and to do other works.

That I used save as csv file script here:

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

When I run it, my output file looks like;

在此处输入图像描述

How can I eliminate blank rows & columns I did not find good way. I just want to save useful cells with this way.

I don't use Windows so I can't check how to do it in VBA but I would use Python and pandas to remove empty rows and columns.

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

Minimal working example.

I uses io.StringIO only to simulate file with data. You should test it with 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 )

Result:

     A    B    C
0  1.0  2.0  3.0
1  4.0  5.0  6.0

Try this code:

' 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM