简体   繁体   中英

Can I export only a range within a sheet using VBA?

I have only just started learning VBA and have built a small application that exports a particular sheet. I want to go one step further and only export a range from that sheet.

I've tried various different coding scenarios but to no avail.

Sub saveSheetToCSV()

    Dim myCSVFileName As String
    Dim tempWB As Workbook

    myCSVFileName = ThisWorkbook.Path & "\" & "EXPORT_" & VBA.Format(VBA.Now, "ddMMyyyy") & ".csv"

    ThisWorkbook.Sheets("Data").Activate

    ActiveSheet.Copy
    Set tempWB = ActiveWorkbook

    With tempWB
    .SaveAs FileName:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
    .Close
    End With
End Sub

Can anyone please confirm what code I would use to just export a range within a sheet? I'm trying to export just the range A2:D24 in the sheet called "Data", rather than the whole sheet as what the current code above does. Thanks.

Copy Range to new Sheet in new Workbook. Save As. Close.

    Dim myCSVFileName As String
    Dim tempWB As Workbook

    myCSVFileName = ThisWorkbook.Path & "\" & "EXPORT_" & VBA.Format(VBA.Now, "ddMMyyyy") & ".csv"
    'Create new Workbook.
    Set tempWB = Workbooks.Add
    'Copy Range
    ThisWrokbook.Sheets("SheetNameWithRange").Range("A1:Z40").Copy    
    With tempWB
        'Paste Range
        .Worksheets(1).Range("A1").Paste 'Or Paste as Values to not retain Links/Formulas
        'Save and Close
        .SaveAs FileName:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
        .Close
    End With

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