Excel VBA -导出CSV -仅包含数据的行

xzv2uavs  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(138)

当涉及到VBA我是一个非常初学者.我创建了一个宏后,在网上寻找导出CSV.我遇到的问题是,它是导出一切,甚至是空白单元格.我看了多篇文章在这里,我仍然困惑于什么/如何我需要处理代码.任何提示将不胜感激.我已经粘贴了我目前的代码下面.
此外,A/B列是必填字段,将用于确定行是否为空。如果A/B列中没有数据,则该行为空。
TIA

Sub ExportAsCSV()

    Dim MyFileName As String
    Dim CurrentWB As Workbook, TempWB As Workbook
    Dim dtToday As String
    
    dtToday = Format(Date, "MM.DD.YY")
    
    Set CurrentWB = ActiveWorkbook
    ActiveWorkbook.ActiveSheet.UsedRange.Copy

    Set TempWB = Application.Workbooks.Add(1)
    
    With TempWB.Sheets(1).Range("A1")
        .PasteSpecial xlPasteValues
        .PasteSpecial xlPasteFormats
    End With

    MyFileName = CurrentWB.Path & "\" & "ARMs Upload " & dtToday & ".csv"
    'Optionally, comment previous line and uncomment next one to save as the current sheet name
    'MyFileName = CurrentWB.Path & "\" & CurrentWB.ActiveSheet.Name & ".csv"

    Application.DisplayAlerts = False
    TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
    TempWB.Close SaveChanges:=False
    Application.DisplayAlerts = True
End Sub

导出CSV时没有blacnk单元格。它导出了所有单元格,这会导致另一个系统导入数据时出现问题。

envsm3lx

envsm3lx1#

粘贴后,可以删除任何不完整的行:

Sub ExportAsCSV()

    Dim MyFileName As String
    Dim CurrentWB As Workbook, TempWB As Workbook
    Dim dtToday As String, rng As Range, i As Long
    
    dtToday = Format(Date, "MM.DD.YY")
    
    Set CurrentWB = ActiveWorkbook
    Set rng = CurrentWB.ActiveSheet.UsedRange '<<<
    rng.copy

    Set TempWB = Application.Workbooks.Add(1)
    
    With TempWB.Sheets(1).Range("A1")
        .PasteSpecial xlPasteValues
        .PasteSpecial xlPasteFormats
    End With
    
    'remove any pasted rows without a value in Cols A and B
    For i = rng.Rows.Count To 2 Step -1
        With TempWB.Sheets(1).Rows(i)
            If Application.CountA(.Range("A1:B1")) < 2 Then .Delete
        End With
    Next i

    MyFileName = CurrentWB.Path & "\" & "ARMs Upload " & dtToday & ".csv"
    'Optionally, comment previous line and uncomment next one to save as the current sheet name
    'MyFileName = CurrentWB.Path & "\" & CurrentWB.ActiveSheet.Name & ".csv"

    Application.DisplayAlerts = False
    TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
    TempWB.Close SaveChanges:=False
    Application.DisplayAlerts = True

End Sub

相关问题