VBA to export the selected range in Excel to CSV.

VBA

This article provides a detailed explanation of how to use Excel VBA to export a selected range on an Excel sheet as a CSV file. It includes an example of the code and explains its functionality and how to use it. This script meets the needs of quickly saving a specific dataset to an external file or easily sharing Excel data with other programs.

Used Technologies

  • Microsoft Excel: A platform for data organization and presentation
  • VBA (Visual Basic for Applications): Macro and programming within Excel
  • File I/O: File input/output operations in VBA
  • Excel Object Model: Using objects like Worksheet, Range, Cells, etc.

Features

  • Automatic detection of selected range: Automatically recognizes the cell range selected on Excel
  • CSV file creation: Outputs the data of the selected range in CSV format
  • Customization of file name: Saves the CSV with a file name specified by the user
  • User confirmation: User confirmation is required before executing the process
  • Error handling: Currently, only basic error handling (user confirmation) is implemented
  • Support for a single Excel sheet: Currently, it only outputs the selected range of the active sheet.

Sauce Code

VB
Sub ExportSelectedRangeToCSV()

    ' Declare variables
    Dim filePath As String
    Dim cellData As Variant
    Dim i As Long, j As Long
    Dim userConfirm As VbMsgBoxResult
    Dim fileName As String
    Dim selectedRange As Range
    Dim startRow As Long, startColumn As Long, endRow As Long, endColumn As Long

    ' Initialize
    Set selectedRange = Selection
    
    ' Prompt the user to enter a file name for the CSV
    fileName = InputBox("Please enter the name for the CSV file.")
    
    ' Confirm with the user
    userConfirm = MsgBox("Do you want to create a CSV with the selected range?", vbYesNo)
    
    ' If the user clicked 'Yes'
    If userConfirm = vbYes Then
    
        ' Set the path and name of the file
        filePath = ThisWorkbook.Path & "\" & fileName & ".csv"
        
        ' Get the starting and ending rows and columns of the selected range
        startRow = selectedRange.Row
        startColumn = selectedRange.Column
        endRow = startRow + selectedRange.Rows.Count - 1
        endColumn = startColumn + selectedRange.Columns.Count - 1
        
        ' Read the range of cells into a variable
        cellData = selectedRange.Value
        
        ' Open the file for output
        Open filePath For Output As #1
        
        ' Loop through each row in the array
        For i = 1 To UBound(cellData, 1)
            ' Write the first cell of the row
            Print #1, CStr(cellData(i, 1));
            
            ' Loop through each column in the row
            For j = 2 To UBound(cellData, 2)
                ' Write the cell data, separated by commas
                Print #1, "," & CStr(cellData(i, j));
            Next j
            
            ' Move to the next line in the CSV file
            Print #1,
        Next i
        
        ' Close the file
        Close #1
        
        ' Notify the user that the CSV export was successful
        MsgBox "CSV export was successful."
        
    Else
        ' If the user cancelled the operation
        Exit Sub
    End If

End Sub

' MIT License
' Copyright (c) 2023 [ANJI]
'
' Permission is hereby granted, free of charge, to any person obtaining a copy
' of this software and associated documentation files (the "Software"), to deal
' in the Software without restriction, including without limitation the rights
' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all
' copies or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
' SOFTWARE.

How to Use

  1. Open Excel file: Open the target Excel file and select the sheet to edit.
  2. Open VBA editor: Press Alt + F11 keys to open the VBA editor.
  3. Add a new module: Right-click > Insert > Module to create a new VBA module.
  4. Paste the code: Paste the pre-prepared VBA code into the newly created module.
  5. Run the macro: Close the VBA editor and return to Excel, then press Alt + F8 to run the macro.
  6. Enter the filename: A dialog box appears, enter the name of the CSV file you want to output.
  7. Select the range: Select the cell range in the Excel sheet that you want to export to CSV.
  8. User confirmation: A message box appears, select Yes to proceed with the process.
  9. CSV output: The selected range is output as a CSV file and saved in the destination folder.
  10. Confirmation message: If the CSV output is successful, a confirmation message is displayed.

コメント

タイトルとURLをコピーしました