删除隐藏列将excel范围保存到csv

时间:2015-08-14 08:44:40

标签: excel vba export-to-csv

我做了代码以将excel范围保存到csv
但它的隐藏列也可以帮助删除隐藏的列?

'Sub to select range from excel and save it as CSV
'Added code for paste special    
Private Sub Main()
    Dim sFullFilePath As String
    Dim selectedRange As Range

    sFullFilePath = "C:\MyFileName.csv"
    Set selectedRange = Application.InputBox("Select a range", "Get Range", Type:=8)

    RangeTOCsv sFullFilePath, selectedRange
End Sub

Private Sub RangeTOCsv(sFullFilePath As String, selectedRange As Range)
    Dim workBook As workBook
    Application.DisplayAlerts = False

    selectedRange.Copy
    Set workBook = Workbooks.Add
    With workBook
        .Sheets(1).Select
        ActiveSheet.Range("A1").PasteSpecial Paste:=xlPasteValues
        .SaveAs sFullFilePath, xlCSV
        .Close
    End With
End Sub

1 个答案:

答案 0 :(得分:1)

您需要修改RangeToCsv程序,如下所示:

Private Sub RangeToCsv(sFullFilePath As String, selectedRange As Range)
    Dim rng As Excel.Range
    Dim Workbook As Workbook

    Application.DisplayAlerts = False

    Set rng = selectedRange.SpecialCells(xlCellTypeVisible)
    Set Workbook = Workbooks.Add
    With Workbook
        Call rng.Copy
        .Sheets(1).Range("A1").PasteSpecial Paste:=xlPasteValues
        .SaveAs sFullFilePath, xlCSV
        .Close
    End With
End Sub

在将所选范围粘贴到新工作簿之前,它将按功能SpecialCells进行过滤,参数Type设置为xlCellTypeVisible

执行此操作后,变量rng会存储原始selectedRange范围内的所有可见单元格。