在VBA中将Excel工作表的选定部分保存为CSV

z9smfwbn  于 2023-04-07  发布在  其他
关注(0)|答案(2)|浏览(200)

我写了一段代码,将我的Excel工作表导出为CSV。
是否可以只将Excel工作表的某一部分导出为CSV?
我想导出框架表中的数据(不包括宽度/长度/高度)。

Sub exportSheet(sh As Worksheet, csvFilename As String)

Dim wbNew As Workbook
Set wbNew = Workbooks.Add
Dim folder As FileDialog
Dim xDir As String

Dim wsNew As Worksheet

With wbNew
    sh.Copy wbNew.Sheets(1)
    Set wsNew = wbNew.Sheets(1)
    Set folder = Application.FileDialog(msoFileDialogFolderPicker)
    If folder.Show <> -1 Then Exit Sub
    xDir = folder.SelectedItems(1)
    .SaveAs xDir & "/" & csvFilename, _
      FileFormat:=xlCSVMSDOS, CreateBackup:=False
    .Close False
End With

End Sub
8e2ybdfx

8e2ybdfx1#

我假设您在工作表中使用的是Excel表。我还将为该表指定一个适当的名称,以便更容易使用(在功能区〉表设计〉表名)Name an Excel Table。Excel表在VBA中称为ListObject。您可以在VBA中创建ListObject变量,并使用它复制所需的数据。

Dim lo As ListObject
Set lo = ThisWorkbook.Worksheets("<your sheet name>").ListObjects("<your table name>")

然后,我们不再使用

sh.Copy wbNew.Sheets(1)

你可以用

lo.Range.Copy wbNew.Sheets(1).Range("A1")

这只会将表中包含的数据复制到新文件中。如果您只需要数据,而不需要表头,您可以使用列表对象的DataBodyRange属性:

lo.DataBodyRange.Copy wbNew.Sheets(1).Range("A1")

您可能需要在子例程中为表名传递一个额外的参数。有关详细信息,请参阅Offical VBA Reference on ListObject

2w3rbyxf

2w3rbyxf2#

如果只想导出某个部分,最好编写自己的CSV输出例程,将范围作为输入,并将头设置为布尔值。

Public Sub ExportRangeAsCSV(thisSelection As Range, HeaderLine As String, outputFileName As String)

Dim ffNum As Long
Dim csvLine As String, cellVal As Variant, cellTxt As String
Dim i As Integer, j As Integer

csvLine = ""
ffNum = FreeFile

Open outputFileName For Output As #ffNum
If Not (HeaderLine = "") Then Print #ffNum, HeaderLine
For i = 1 To thisSelection.Rows.Count
    For j = 1 To thisSelection.Columns.Count
        
        cellVal = thisSelection(i, j).Value
        
        Select Case VarType(cellVal)
            Case VbVarType.vbDate
                cellTxt = VBA.Format(cellVal, "dd-mmm-yyyy")
            Case VbVarType.vbCurrency, VbVarType.vbDecimal, VbVarType.vbDouble, VbVarType.vbInteger, VbVarType.vbLong, VbVarType.vbSingle
                cellTxt = cellVal
            Case VbVarType.vbString, VbVarType.vbEmpty
                cellTxt = Chr(34) & cellVal & Chr(34)
            Case Else
                cellTxt = cellVal
        End Select
        csvLine = csvLine & cellTxt & ", "

    Next
    Print #ffNum, Left(csvLine, Len(csvLine) - 2)
    csvLine = ""
Next

Close #ffNum

结束接头
或者使用前面讨论过的方法将数据作为值复制到新工作簿,然后使用内置的SaveAsCSV在此处输入链接描述

相关问题