Skip to Content
Course content

9.3 Importing and Exporting Data.

Importing and exporting data are essential operations in VBA, especially when working with Excel files, databases, or text files. These processes allow you to transfer data from external sources into your VBA-enabled application and export data from your application to other formats or external systems.

In this section, we’ll cover various methods and techniques for importing and exporting data using VBA, focusing on Excel files, CSV, and text files.

1. Importing Data into Excel Using VBA

VBA allows you to import data from various sources like text files, CSV files, or other Excel workbooks. The most common method for importing data into Excel is using the Workbooks.Open method for Excel files or QueryTables for CSV and text files.

1.1 Importing Data from Another Excel Workbook

You can import data from another Excel workbook by opening the workbook and copying data from it.

Sub ImportFromAnotherWorkbook()
    Dim sourceWorkbook As Workbook
    Dim targetWorkbook As Workbook
    Dim sourceSheet As Worksheet
    Dim targetSheet As Worksheet
    
    ' Set references to workbooks and worksheets
    Set targetWorkbook = ThisWorkbook
    Set targetSheet = targetWorkbook.Sheets("Sheet1")
    Set sourceWorkbook = Workbooks.Open("C:\path\to\sourcefile.xlsx")
    Set sourceSheet = sourceWorkbook.Sheets("Sheet1")
    
    ' Copy data from source to target
    sourceSheet.Range("A1:C10").Copy
    targetSheet.Range("A1").PasteSpecial xlPasteValues
    
    ' Close the source workbook
    sourceWorkbook.Close False
End Sub

In this example:

  • Workbooks.Open opens the source Excel workbook.
  • Range.Copy and PasteSpecial are used to copy and paste the data as values into the target sheet.

1.2 Importing Data from CSV or Text File

You can import data from CSV or text files using the QueryTables method or the TextFile method. The QueryTables method is particularly useful for importing structured data from CSV files.

Sub ImportCSV()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")
    
    ' Import CSV file
    ws.QueryTables.Add Connection:="TEXT;C:\path\to\file.csv", Destination:=ws.Range("A1")
    With ws.QueryTables(1)
        .TextFileParseType = xlDelimited
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileCommaDelimiter = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

In this example:

  • QueryTables.Add is used to define the source file (CSV) and destination range.
  • TextFileCommaDelimiter is set to True for CSV files, but this can be adjusted based on the delimiter used in the text file (e.g., tab, semicolon).

2. Exporting Data from Excel Using VBA

You can export data from Excel to other formats, such as CSV, text files, or even another Excel workbook, using VBA. The most common methods are the SaveAs method for saving Excel files in different formats, and the FileSystemObject for exporting to text or CSV files.

2.1 Exporting Data to CSV File

To export data from an Excel worksheet to a CSV file, you can use the SaveAs method.

Sub ExportToCSV()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")
    
    ' Save the worksheet as a CSV file
    ws.SaveAs "C:\path\to\exportedfile.csv", FileFormat:=xlCSV
End Sub

In this example:

  • SaveAs saves the active worksheet as a CSV file at the specified location.
  • FileFormat:=xlCSV ensures the file is saved in CSV format.

2.2 Exporting Data to Text File

If you want to export data to a text file (e.g., tab-delimited or space-separated), you can use the FileSystemObject to write each row to a file.

Sub ExportToTextFile()
    Dim fso As Object
    Dim txtFile As Object
    Dim ws As Worksheet
    Dim r As Range
    Dim i As Integer
    Dim j As Integer
    Dim rowValues As String
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ws = ThisWorkbook.Sheets("Sheet1")
    Set txtFile = fso.CreateTextFile("C:\path\to\exportedfile.txt", True)
    
    ' Loop through each row in the range and write to the text file
    For Each r In ws.Range("A1:C10").Rows
        rowValues = ""
        For j = 1 To r.Cells.Count
            rowValues = rowValues & r.Cells(1, j).Value & vbTab ' Tab-separated values
        Next j
        txtFile.WriteLine Left(rowValues, Len(rowValues) - 1) ' Remove trailing tab
    Next r
    
    txtFile.Close
End Sub

In this example:

  • FileSystemObject is used to create a text file.
  • WriteLine writes each row of data to the text file, using vbTab to separate values.

3. Handling Special Data Formats

When exporting data to formats other than CSV or text, you may need to handle specific data types, such as dates or numbers with special formatting.

3.1 Exporting Data with Custom Formats (e.g., Date and Currency)

You can use the NumberFormat property to export formatted data:

Sub ExportWithFormat()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")
    
    ' Format columns (e.g., Date and Currency)
    ws.Range("A1:A10").NumberFormat = "mm/dd/yyyy"
    ws.Range("B1:B10").NumberFormat = "$#,##0.00"
    
    ' Save as CSV with the formatted data
    ws.SaveAs "C:\path\to\formatted_export.csv", FileFormat:=xlCSV
End Sub

In this example:

  • The NumberFormat property is used to apply custom formats to the data (e.g., date and currency).
  • The formatted data is then saved as a CSV file.

4. Importing and Exporting Data Between Excel and Access

If you're working with databases, VBA can also help import and export data between Excel and Access.

4.1 Importing Data from Access to Excel

You can use ADO (ActiveX Data Objects) or DAO (Data Access Objects) to retrieve data from an Access database and import it into Excel.

Sub ImportFromAccess()
    Dim conn As Object
    Dim rs As Object
    Dim sqlQuery As String
    Dim ws As Worksheet
    
    ' Set references to worksheet and database
    Set ws = ThisWorkbook.Sheets("Sheet1")
    Set conn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")
    
    ' Open connection to Access database
    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\path\to\yourdatabase.accdb;"
    
    ' Define SQL query to retrieve data
    sqlQuery = "SELECT * FROM TableName"
    
    ' Execute query and get recordset
    rs.Open sqlQuery, conn
    
    ' Transfer data to Excel
    ws.Range("A1").CopyFromRecordset rs
    
    ' Close the connection
    rs.Close
    conn.Close
End Sub

In this example:

  • ADO is used to connect to an Access database and retrieve data into an Excel worksheet.

4.2 Exporting Data from Excel to Access

Sub ExportToAccess()
    Dim conn As Object
    Dim sqlQuery As String
    Dim ws As Worksheet
    
    ' Set references to worksheet and database
    Set ws = ThisWorkbook.Sheets("Sheet1")
    Set conn = CreateObject("ADODB.Connection")
    
    ' Open connection to Access database
    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\path\to\yourdatabase.accdb;"
    
    ' Export data to Access table
    sqlQuery = "INSERT INTO TableName (Field1, Field2) VALUES ('" & ws.Range("A1").Value & "', '" & ws.Range("B1").Value & "')"
    conn.Execute sqlQuery
    
    ' Close the connection
    conn.Close
End Sub

In this example:

  • Data from Excel is inserted into an Access database using SQL commands.

5. Summary of Importing and Exporting Data

  • Importing Data: Use Workbooks.Open for Excel files, QueryTables.Add for CSV and text files, and ADO/DAO for database connections.
  • Exporting Data: Use SaveAs to export to formats like CSV, text, or Excel. Use FileSystemObject for more complex file writing operations.
  • Handling Special Formats: Customize number and date formats using NumberFormat.
  • Database Integration: Use ADO or DAO to import/export data between Excel and Access.

By mastering these importing and exporting techniques, you can create automated workflows that integrate Excel with other applications, making your VBA projects more powerful and flexible.

Commenting is not enabled on this course.