Export vba from excel

This tutorial will cover the ways to import data from Excel into an Access Table and ways to export Access objects (Queries, Reports, Tables, or Forms) to Excel.

Import Excel File Into Access

To import an Excel file to Access, use the acImport option of DoCmd.TransferSpreadsheet :

DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "Table1", "C:TempBook1.xlsx", True

Or you can use DoCmd.TransferText to import a CSV file:

DoCmd.TransferText acLinkDelim, , "Table1", "C:TempBook1.xlsx", True

Import Excel to Access Function

This function can be used to import an Excel file or CSV file into an Access Table:

Public Function ImportFile(Filename As String, HasFieldNames As Boolean, TableName As String) As Boolean
' Example usage: call ImportFile ("Select an Excel File",  "Excel Files", "*.xlsx",  "C:" , True,True, "ExcelImportTest", True, True,false,True)

    On Error GoTo err_handler
  
    If (Right(Filename, 3) = "xls") Or ((Right(Filename, 4) = "xlsx")) Then
                DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, TableName, Filename, blnHasFieldNames
            End If
    If (Right(Filename, 3) = "csv") Then
                DoCmd.TransferText acLinkDelim, , TableName, Filename, True
    End If
    
Exit_Thing:

    'Clean up
    'Check if our linked in Excel table already exists... and delete it if so
    If ObjectExists("Table", TableName) = True Then DropTable (TableName)
    Set colWorksheets = Nothing

    Exit Function
    
err_handler:
    If (Err.Number = 3086 Or Err.Number = 3274 Or Err.Number = 3073) And errCount < 3 Then
        errCount = errCount + 1

    ElseIf Err.Number = 3127 Then
        MsgBox "The fields in all the tabs are the same. Please make sure that each sheet has the exact column names if you wish to import mulitple", vbCritical, "MultiSheets not identical"
        ImportFile = False
        GoTo Exit_Thing
    Else
        MsgBox Err.Number & " - " & Err.Description
        ImportFile = False
        GoTo Exit_Thing
        Resume
    End If
End Function

You can call the function like this:

Private Sub ImportFile_Example()
 Call VBA_Access_ImportExport.ImportFile("C:TempBook1.xlsx", True, "Imported_Table_1")
End Sub

Access VBA Export to New Excel File

To export an Access object to a new Excel file, use the DoCmd.OutputTo method or the DoCmd.TransferSpreadsheet method:

Export Query to Excel

This line of VBA code will export a Query to Excel using DoCmd.OutputTo:

DoCmd.OutputTo acOutputQuery, "Query1", acFormatXLSX, "c:tempExportedQuery.xls"

Or you can use the DoCmd.TransferSpreadsheet method instead:

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "Query1", "c:tempExportedQuery.xls", True

Note: This code exports to XLSX format. Instead you can update the arguments to export to a CSV or XLS file format instead (ex. acFormatXLSX to acFormatXLS).

Export Report to Excel

This line of code will export a Report to Excel using DoCmd.OutputTo:

DoCmd.OutputTo acOutputReport, "Report1", acFormatXLSX, "c:tempExportedReport.xls"

Or you can use the DoCmd.TransferSpreadsheet method instead:

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "Report1", "c:tempExportedReport.xls", True

Export Table to Excel

This line of code will export a Table to Excel using DoCmd.OutputTo:

DoCmd.OutputTo acOutputTable, "Table1", acFormatXLSX, "c:tempExportedTable.xls"

Or you can use the DoCmd.TransferSpreadsheet method instead:

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "Table1", "c:tempExportedTable.xls", True

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Export Form to Excel

This line of code will export a Form to Excel using DoCmd.OutputTo:

DoCmd.OutputTo acOutputForm, "Form1", acFormatXLSX, "c:tempExportedForm.xls"

Or you can use the DoCmd.TransferSpreadsheet method instead:

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "Form1", "c:tempExportedForm.xls", True

Export to Excel Functions

These one line commands work great to export to a new Excel file. However, they will not be able to export into an existing workbook.  In the section below we introduce functions that allow you to append your export to an existing Excel file.

Below that, we’ve included some additional functions to export to new Excel files, including error handling and more.

Export to Existing Excel File

The above code examples work great to export Access objects to a new Excel file.  However, they will not be able to export into an existing workbook.

To export Access objects to an existing Excel workbook we’ve created the following function:

Public Function AppendToExcel(strObjectType As String, strObjectName As String, strSheetName As String, strFileName As String)

    Dim rst As DAO.Recordset
    Dim ApXL As Excel.Application
    Dim xlWBk As Excel.Workbook
    Dim xlWSh As Excel.Worksheet
    Dim intCount As Integer
    Const xlToRight As Long = -4161
    Const xlCenter As Long = -4108
    Const xlBottom As Long = -4107
    Const xlContinuous As Long = 1
      
    Select Case strObjectType

    Case "Table", "Query"
        Set rst = CurrentDb.OpenRecordset(strObjectName, dbOpenDynaset, dbSeeChanges)
    Case "Form"
        Set rst = Forms(strObjectName).RecordsetClone
    Case "Report"
        Set rst = CurrentDb.OpenRecordset(Reports(strObjectName).RecordSource, dbOpenDynaset, dbSeeChanges)
    End Select

    If rst.RecordCount = 0 Then
        MsgBox "No records to be exported.", vbInformation, GetDBTitle
    Else
        On Error Resume Next
        Set ApXL = GetObject(, "Excel.Application")
        If Err.Number <> 0 Then
            Set ApXL = CreateObject("Excel.Application")
        End If
        Err.Clear

        ApXL.Visible = False
        
        Set xlWBk = ApXL.Workbooks.Open(strFileName)
        Set xlWSh = xlWBk.Sheets.Add
        xlWSh.Name = Left(strSheetName, 31)

        
        xlWSh.Range("A1").Select
        Do Until intCount = rst.fields.Count
            ApXL.ActiveCell = rst.fields(intCount).Name
            ApXL.ActiveCell.Offset(0, 1).Select
            intCount = intCount + 1
        Loop

        rst.MoveFirst
        
        xlWSh.Range("A2").CopyFromRecordset rst

        With ApXL
            .Range("A1").Select
            .Range(.Selection, .Selection.End(xlToRight)).Select
            .Selection.Interior.Pattern = xlSolid
            .Selection.Interior.PatternColorIndex = xlAutomatic
            .Selection.Interior.TintAndShade = -0.25
            .Selection.Interior.PatternTintAndShade = 0
            .Selection.Borders.LineStyle = xlNone
            .Selection.AutoFilter
            .Cells.EntireColumn.AutoFit
            .Cells.EntireRow.AutoFit
            .Range("B2").Select
            .ActiveWindow.FreezePanes = True
            .ActiveSheet.Cells.Select
            .ActiveSheet.Cells.WrapText = False
            .ActiveSheet.Cells.EntireColumn.AutoFit
            xlWSh.Range("A1").Select
            .Visible = True
        End With

        'xlWB.Close True
        'Set xlWB = Nothing
        'ApXL.Quit
        'Set ApXL = Nothing
    End If
End Function

You can use the function like this:

Private Sub AppendToExcel_Example()
    Call VBA_Access_ImportExport.ExportToExcel("Table", "Table1", "VBASheet", "C:TempTest.xlsx")
End Sub

Notice you are asked to define:

  • What to Output? Table, Report, Query, or Form
  • Object Name
  • Output Sheet Name
  • Output File Path and Name.

VBA Programming | Code Generator does work for you!

Export SQL Query to Excel

Instead you can export an SQL query to Excel using a similar function:

Public Function AppendToExcelSQLStatemet(strsql As String, strSheetName As String, strFileName As String)
    Dim strQueryName As String
    Dim ApXL As Excel.Application
    Dim xlWBk As Excel.Workbook
    Dim xlWSh As Excel.Worksheet
    Dim intCount As Integer
    Const xlCenter As Long = -4108
    Const xlBottom As Long = -4107
    Const xlVAlignCenter = -4108
    Const xlContinuous As Long = 1
    Dim qdf As DAO.QueryDef
    Dim rst As DAO.Recordset
    
    strQueryName = "tmpQueryToExportToExcel"

    If ObjectExists("Query", strQueryName) Then
        CurrentDb.QueryDefs.Delete strQueryName
    End If
    Set qdf = CurrentDb.CreateQueryDef(strQueryName, strsql)
    Set rst = CurrentDb.OpenRecordset(strQueryName, dbOpenDynaset)

    If rst.RecordCount = 0 Then
        MsgBox "No records to be exported.", vbInformation, GetDBTitle
    Else
        On Error Resume Next
        Set ApXL = GetObject(, "Excel.Application")
        If Err.Number <> 0 Then
            Set ApXL = CreateObject("Excel.Application")
        End If
        Err.Clear

        ApXL.Visible = False
        
        Set xlWBk = ApXL.Workbooks.Open(strFileName)
        Set xlWSh = xlWBk.Sheets.Add
        xlWSh.Name = Left(strSheetName, 31)

        
        xlWSh.Range("A1").Select
        Do Until intCount = rst.fields.Count
            ApXL.ActiveCell = rst.fields(intCount).Name
            ApXL.ActiveCell.Offset(0, 1).Select
            intCount = intCount + 1
        Loop

        rst.MoveFirst
        
        xlWSh.Range("A2").CopyFromRecordset rst

        With ApXL
            .Range("A1").Select
            .Range(.Selection, .Selection.End(xlToRight)).Select
            .Selection.Interior.Pattern = xlSolid
            .Selection.Interior.PatternColorIndex = xlAutomatic
            .Selection.Interior.TintAndShade = -0.25
            .Selection.Interior.PatternTintAndShade = 0
            .Selection.Borders.LineStyle = xlNone
            .Selection.AutoFilter
            .Cells.EntireColumn.AutoFit
            .Cells.EntireRow.AutoFit
            .Range("B2").Select
            .ActiveWindow.FreezePanes = True
            .ActiveSheet.Cells.Select
            .ActiveSheet.Cells.WrapText = False
            .ActiveSheet.Cells.EntireColumn.AutoFit
            xlWSh.Range("A1").Select
            .Visible = True
        End With


        'xlWB.Close True
        'Set xlWB = Nothing
        'ApXL.Quit
        'Set ApXL = Nothing
    End If
End Function

Called like this:

Private Sub AppendToExcelSQLStatemet_Example()
    Call VBA_Access_ImportExport.ExportToExcel("SELECT * FROM Table1", "VBASheet", "C:TempTest.xlsx")
End Sub

Where you are asked to input:

  • SQL Query
  • Output Sheet Name
  • Output File Path and Name.

Function to Export to New Excel File

These functions allow you to export Access objects to a new Excel workbook. You might find them more useful than the simple single lines at the top of the document.

Public Function ExportToExcel(strObjectType As String, strObjectName As String, Optional strSheetName As String, Optional strFileName As String)

    Dim rst As DAO.Recordset
    Dim ApXL As Object
    Dim xlWBk As Object
    Dim xlWSh As Object
    Dim intCount As Integer
    Const xlToRight As Long = -4161
    Const xlCenter As Long = -4108
    Const xlBottom As Long = -4107
    Const xlContinuous As Long = 1

    On Error GoTo ExportToExcel_Err
    DoCmd.Hourglass True

    Select Case strObjectType

    Case "Table", "Query"
        Set rst = CurrentDb.OpenRecordset(strObjectName, dbOpenDynaset, dbSeeChanges)
    Case "Form"
        Set rst = Forms(strObjectName).RecordsetClone
    Case "Report"
        Set rst = CurrentDb.OpenRecordset(Reports(strObjectName).RecordSource, dbOpenDynaset, dbSeeChanges)
    End Select

    If rst.RecordCount = 0 Then
        MsgBox "No records to be exported.", vbInformation, GetDBTitle
        DoCmd.Hourglass False
    Else
        On Error Resume Next
        Set ApXL = GetObject(, "Excel.Application")
        If Err.Number <> 0 Then
            Set ApXL = CreateObject("Excel.Application")
        End If
        Err.Clear
        On Error GoTo ExportToExcel_Err

        Set xlWBk = ApXL.Workbooks.Add
        ApXL.Visible = False

        Set xlWSh = xlWBk.Worksheets("Sheet1")
        If Len(strSheetName) > 0 Then
            xlWSh.Name = Left(strSheetName, 31)
        End If

        xlWSh.Range("A1").Select
        Do Until intCount = rst.fields.Count
            ApXL.ActiveCell = rst.fields(intCount).Name
            ApXL.ActiveCell.Offset(0, 1).Select
            intCount = intCount + 1
        Loop

        rst.MoveFirst
        
        xlWSh.Range("A2").CopyFromRecordset rst

        With ApXL
            .Range("A1").Select
            .Range(.Selection, .Selection.End(xlToRight)).Select
            .Selection.Interior.Pattern = xlSolid
            .Selection.Interior.PatternColorIndex = xlAutomatic
            .Selection.Interior.TintAndShade = -0.25
            .Selection.Interior.PatternTintAndShade = 0
            .Selection.Borders.LineStyle = xlNone
            .Selection.AutoFilter
            .Cells.EntireColumn.AutoFit
            .Cells.EntireRow.AutoFit
            .Range("B2").Select
            .ActiveWindow.FreezePanes = True
            .ActiveSheet.Cells.Select
            .ActiveSheet.Cells.WrapText = False
            .ActiveSheet.Cells.EntireColumn.AutoFit
            xlWSh.Range("A1").Select
            .Visible = True
        End With

retry:
        If FileExists(strFileName) Then
            Kill strFileName
        End If
        If strFileName <> "" Then
            xlWBk.SaveAs strFileName, FileFormat:=56
        End If
        
        rst.Close
        Set rst = Nothing
        DoCmd.Hourglass False
    End If

ExportToExcel_Exit:
    DoCmd.Hourglass False
    Exit Function

ExportToExcel_Err:
    DoCmd.SetWarnings True
    MsgBox Err.Description, vbExclamation, Err.Number
    DoCmd.Hourglass False
    Resume ExportToExcel_Exit

End Function

The function can be called like this:

Private Sub ExportToExcel_Example()
 Call VBA_Access_ImportExport.ExportToExcel("Table", "Table1", "VBASheet")
End Sub

We can export the data from Microsoft Excel to Microsoft Access by using VBA. Below is the VBA code and process which you need to paste in the code module of the file.

1. Open Excel
2. Press ALT + F11
3. VBA Editor will OPEN
4. Click anywhere in the Project Window
5. Click on Insert
6. Click on Module

image1

7. In the Code Window, Copy and Paste the below mentioned Code

Sub ADOFromExcelToAccess()
‘ exports data from the active worksheet to a table in an Access database
‘ this procedure must be edited before use
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
‘ connect to the Access database
Set cn = New ADODB.Connection
cn.Open «Provider=Microsoft.Jet.OLEDB.4.0; » & _
«Data Source=C:FolderNameDataBaseName.mdb;»
‘ open a recordset
Set rs = New ADODB.Recordset
rs.Open «TableName», cn, adOpenKeyset, adLockOptimistic, adCmdTable
‘ all records in a table
r = 3 ‘ the start row in the worksheet
Do While Len(Range(«A» & r).Formula) > 0
‘ repeat until first empty cell in column A
With rs
.AddNew ‘ create a new record
‘ add values to each field in the record
.Fields(«FieldName1») = Range(«A» & r).Value
.Fields(«FieldName2») = Range(«B» & r).Value
.Fields(«FieldNameN») = Range(«C» & r).Value
‘ add more fields if necessary…
.Update ‘ stores the new record
End With
r = r + 1 ‘ next row
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub

image2

8. Once this is pasted, go to the Excel file
9. Click on the VIEW Tab on the ribbon
10. Click on Macros
11. Click on View Macros
12. The Shortcut Key to View Macros is ALT + F8
13. A Window will popup

image3

14. Select the Macro
15. Here the Macro is named as “ADOFromExcelToAccess”
16. Select the Macro “ADOFromExcelToAccess”
17. Click on Run
18. Click OK to close the Box

This is how we can Export data from Excel to Access by using VBA in Microsoft Excel.

Импорт, экспорт и удаление модуля в редакторе VBA. Программный экспорт-импорт модуля из одной рабочей книги Excel в другую с помощью кода VBA Excel.

1. Откройте рабочую книгу Excel, в которую планируете импортировать модуль. Для импорта модуля в Личную книгу макросов, откройте любую книгу.

2. Откройте редактор VBA сочетанием клавиш Alt+F11 (в этом сочетании используется левая клавиша Alt). Обратите внимание на наличие в окне редактора VBA окна проводника «Project-VBAProject», обычно, расположенного слева. При отсутствии, отобразите его через главное меню, выбрав «View» — «Project Explorer».

3. В окне проводника «Project-VBAProject» найдите строку «VBAProject (ИмяКниги)», где «ИмяКниги» — это имя книги, в которую вы собираетесь импортировать модуль. Если вы желаете импортировать модуль в Личную книгу макросов, строка называется «VBAProject (PERSONAL.XLSB)». Если у вас нет Личной книги макросов — создайте ее.

4. У выбранной строки раскройте все крестики слева.

5. Откройте контекстное меню, кликнув правой кнопкой мыши на строке «ЭтаКнига», и выберите в нем пункт «Import File…».

6. В открывшемся окне выбора файла найдите импортируемый модуль с расширением .bas и дважды кликните по нему, или кликните один раз и нажмите кнопку «Открыть». Модуль импортирован и отобразился в проводнике под именем «Module» с очередным номером, независимо от имени импортируемого файла.

7. Если вы импортировали модуль в Книгу Excel 2007-2016 с расширением .xlsx, ее необходимо будет пересохранить как «Книга Excel с поддержкой макросов (.xlsm)», иначе импортированный модуль не сохранится.

Инструкцию с картинками вы можете посмотреть здесь в параграфе «Пользовательская функция «СуммаПрописью».

Экспорт модуля в редакторе VBA

1. Откройте рабочую книгу Excel, из которой вы планируете экспортировать модуль. Для экспорта модуля из Личной книги макросов, откройте любую книгу.

2. Откройте редактор VBA сочетанием клавиш Alt+F11 и в окне проводника «Project-VBAProject» найдите экспортируемый модуль.

3. Откройте контекстное меню, кликнув правой кнопкой мыши на экспортируемом модуле, и выберите в нем пункт «Export File…».

4. В открывшемся окне выберите папку, куда следует сохранить экспортируемый модуль, если необходимо, измените название сохраняемого файла, и нажмите кнопку «Сохранить». Модуль экспортирован и отобразился в выбранном каталоге с указанным именем и расширением .bas.

Удаление модуля в редакторе VBA

1. В окне проводника «Project-VBAProject» найдите удаляемый модуль.

2. Откройте контекстное меню, кликнув правой кнопкой мыши на удаляемом модуле, и выберите в нем пункт «Remove Module…» с номером удаляемого модуля.

3. VBA Excel предложит экспортировать модуль перед удалением, нажмите «Да», если хотите сохранить модуль, или «Нет», чтобы удалить без сохранения.

Как удалить стандартный модуль с помощью кода VBA Excel, смотрите в последнем параграфе статьи Программное создание модуля.

Программный экспорт-импорт модуля

Пример программного экспорта стандартного модуля "Module1" из книги "Книга2.xlsm" и импорта его в книгу "Книга3.xlsm" с помощью кода VBA Excel:

Sub ExportImportModule()

    Workbooks(«Книга2.xlsm»).VBProject.VBComponents(«Module1»).Export «C:ТестоваяModule1.bas»

    Workbooks(«Книга3.xlsm»).VBProject.VBComponents.Import «C:ТестоваяModule1.bas»

End Sub

Если в книге "Книга3.xlsm" уже присутствует модуль с именем "Module1", то импортированному модулю будет присвоен другой номер.

Программное удаление модуля

Код VBA Excel для программного удаления стандартного модуля с именем "Module24":

Sub RemoveModule()

    With ThisWorkbook.VBProject

        .VBComponents.Remove .VBComponents(«Module24»)

    End With

End Sub

Замените имя "Module24" на имя своего модуля, который вы хотите безвозвратно удалить.


Is there a clean way to extract the VBA from a spreadsheet and store it in a repository.

The spreadsheets hardly ever change but the VBA does. Storing the whole spreadsheet in the repository makes it difficult to do diffs across the different VBA revisions to see what code has changed and who changed it.

We use VBA 6.5 / Excel 2003.

Community's user avatar

asked May 11, 2009 at 2:45

rbrayb's user avatar

Previous versions of Excel and Access (prior to 2003) supported VBA Source Code Version Control via an add-in. I have used this very effectively in Office 2000.

Visual SourceSafe (VSS) support for VBA was dropped with the release of Office 2003, but the add-in that was shipped with Office XP Developer apparently works with Office 2003.

Microsoft Knowledge Base articles:

  • Using Visual SourceSafe with Documents and VBA Code

  • Using the Visual SourceSafe Add-In with the Visual Basic Environment

Failing that you can use this code to extract the VBA code (from here but it was missing the final object cleanups). Read the webpage for caveats:

option explicit

Const vbext_ct_ClassModule = 2
Const vbext_ct_Document = 100
Const vbext_ct_MSForm = 3
Const vbext_ct_StdModule = 1

Main

Sub Main
    Dim xl
    Dim fs
    Dim WBook
    Dim VBComp
    Dim Sfx
    Dim ExportFolder

    If Wscript.Arguments.Count <> 1 Then
        MsgBox "As the only argument, give the FULL path to an XLS file to extract all the VBA from it."
    Else

        Set xl = CreateObject("Excel.Application")
        Set fs = CreateObject("Scripting.FileSystemObject")

        xl.Visible = true

        Set WBook = xl.Workbooks.Open(Trim(wScript.Arguments(0)))

        ExportFolder = WBook.Path & "" & fs.GetBaseName(WBook.Name)

        fs.CreateFolder(ExportFolder)

        For Each VBComp In WBook.VBProject.VBComponents
            Select Case VBComp.Type
                Case vbext_ct_ClassModule, vbext_ct_Document
                    Sfx = ".cls"
                Case vbext_ct_MSForm
                    Sfx = ".frm"
                Case vbext_ct_StdModule
                    Sfx = ".bas"
                Case Else
                    Sfx = ""
            End Select
            If Sfx <> "" Then
                On Error Resume Next
                Err.Clear
                VBComp.Export ExportFolder & "" & VBComp.Name & Sfx
                If Err.Number <> 0 Then
                    MsgBox "Failed to export " & ExportFolder & "" & VBComp.Name & Sfx
                End If
                On Error Goto 0
            End If
        Next

        xl.Quit

        Set fs = Nothing
        Set xl = Nothing

    End If
End Sub

answered May 11, 2009 at 2:54

Mitch Wheat's user avatar

Mitch WheatMitch Wheat

294k43 gold badges465 silver badges540 bronze badges

1

The other answers to this question address it pretty well, but if you’re just starting to write the code, look into VSTO. It provides managed code for Office, and best of all, you can even do it in C# or whatever .NET language strikes your fancy. It also works with Excel 2003, which is a bonus, in your case.

answered May 11, 2009 at 3:12

Eric's user avatar

EricEric

91.1k12 gold badges112 silver badges115 bronze badges

Community's user avatar

answered May 11, 2009 at 3:04

RedBlueThing's user avatar

RedBlueThingRedBlueThing

41.7k17 gold badges98 silver badges122 bronze badges

2

You already have a great answer, but allow me to add an aside.

It is quite possible to keep all of your VBA code in a spreadsheet seperate from the spreadsheet(s) that contains the data. If you do this it might make your comparisons easier.

answered May 11, 2009 at 3:26

JonnyBoats's user avatar

JonnyBoatsJonnyBoats

5,1571 gold badge35 silver badges60 bronze badges

3

VBA Import & Export Add-in for MS Excel

The VBA Import & Export Add-in is an Add-in for Microsoft Excel that allows
you to import and export VBA code to and from Excel Workbooks (.xlsm files)
easily. This allows VBA code to be stored in plain text files alongside the
.xlsm file. This is essential for effectively utilizing Git in a VBA project
(or any other VCS).

Installation

  1. Download the Add-in: VBA-Import-Export.xlam (version 0.4.0)
  2. Add and enable the Add-in in Excel
  3. In Excel, Check the Trust access to the VBA project model check box
    located in Trust Centre -> Trust Centre Settings -> Macro Settings -> Trust access to the VBA project model.

Usage

The add-in can be used from Developer tab of the Excel
ribbon menu
and in the menu of the VBA IDE. Both menus provide the same
commands.

Getting started

  1. Save your .xlsm file into a folder.
  2. Use the Make Config File command to make a CodeExport.config.json file in
    the same folder as the .xlsm file. This records a list of VBA files and
    references.
  3. Use the Export command to export the VBA code. Notice the VBA code present
    in the same folder as your .xlsm file.
  4. Save and close your Excel workbook.
  5. (Optional) Commit the contents of your project directory into Git or any
    other VCS system.

Important:
VBA-project-template
provides config files to ensure Git and text editors play nicely with your
project files.

When you return to work on the VBA project:

  1. (Optional) Checkout a version of your project from Git or the VCS system you
    are using.
  2. Open the Excel workbook (.xlsm file) in Excel.
  3. Use the Import command to import the VBA code from the project directory*
    and the references listed in the configuration file.
  4. Regularly use the Save command to save your changes to the file system while you work.
  5. Use the Make Config File command to update the config file when modules or references are added or removed.
  6. When you’re finished, use the Export command to export your work, then save
    and close the Excel workbook.

* Only files listed in the configuration file will be imported.

Safety tips

Here’s some tips to avoid loosing data while using this Add-in:

  • Do regular backups! Use the method that you won’t forget. My favourite method is to use Git. Any versioning system would also work.
  • If you make changes in the Excel document, don’t edit the files in the file system before you Export. The inevitable Export will overwrite your changes.
  • If you make changes in the Excel document, don’t Import before using Save or Export. You will just overwrite your changes with what you started with.
  • Save regularly to avoid making the mistake above.

The configuration file

The CodeExport.config.json file declares what gets imported and exported from
an Excel workbook. The config file must be in the same directory as the .xlsm
file. The config file can be edited in a text editor to make advanced
adjustments that the Make Config File command cannot do. A comprehensive
example config file can be found at
test-projects/comprehensive/CodeExport.config.json.
The config file uses the JSON file format
and the configuration properties are:

  • VBAProject Name — The name of the VBAProject. Will be set on import. Must
    not contain any spaces.
  • Module Paths — A file system path for every VBA module that will be imported
    and exported by CodeExport. These may be relative or absolute paths.
  • Base Path — A prefix to be prepended to all relative paths in
    Module Paths.
  • References — A list of reference definitions. Each reference described will
    be referenced on import and dereferenced on export.

Importing, Saving & Exporting

The Import command will:

  • Import all the modules specified in the Module Paths configuration property.
    Existing modules in the Excel file will be overwritten.
  • Add all library references declared in the References configuration
    property. Existing library references in the Excel file will be overwritten.
  • Set the VBAProject name as declared in the VBAProject Name configuration
    property.

The Save command will:

  • Export all the modules specified in the Module Paths configuration property.
    Existing files in the file system will be overwritten.

The Export command will:

  • Do the same as the Save command.
  • Dereference libraries declared in the References configuration property.

Support

You can submit questions, requests and bug reports to the
issues list.
Github pull requests are also welcome.

Authors and Attribution

  • Scott Spence — Author
    (spences10/VBA-IDE-Code-Export)
  • Matthew Palermo — Author
    (mattpalermo/VBA-Import-Export)
  • Tim Hall — Author of the library VBA-JSON
  • Kevin Conner — Author of the Save action

See Also

  • vba-blocks — A VBA package manager in
    development by Tim Hall. It will hopefully supersede this add-in.
  • VBA-IDE-Code-Export — Scott
    Spence’s version of this add-in.

Понравилась статья? Поделить с друзьями:
  • Export to excel yii2
  • Export to excel with php
  • Export to excel sas
  • Export excel into oracle
  • Export excel data to csv file