Access vba as excel application

Access для Microsoft 365 Access 2021 Access 2019 Access 2016 Access 2013 Access 2010 Access 2007 Еще…Меньше

Примечание: Функция, метод, объект или свойство, описанные в данном разделе, отключаются, если служба обработки выражений Microsoft Jet выполняется в режиме песочницы, который не позволяет рассчитывать потенциально небезопасные выражения. Для получения дополнительных сведений выполните в справке поиск по словам «режим песочницы».

Создает и возвращает ссылку на объект ActiveX.

Синтаксис

CreateObject
(

класс
[, имя_сервера] )

Функция CreateObject имеет следующие аргументы:

Аргумент

Описание


класс

Обязательный аргумент. Variant (String). Имя приложения и класс создаваемого объекта.


имя_сервера

Необязательный аргумент. Variant (String). Имя сетевого сервера, где будет создан объект. Если имя_сервера является пустой строкой («»), используется локальный компьютер.

Аргумент классаргумент использует синтаксис имя_приложения.тип_объекта и содержит следующие части:

Элемент

Описание


имя_приложения

Обязательный аргумент. Variant (String). Имя приложения, предоставляющего объект.


тип_объекта

Обязательный аргумент. Variant (String). Тип (класс) объекта, который требуется создать.

Замечания

В каждом приложении, поддерживающем автоматизацию, имеется хотя бы один тип объекта. Например, в приложении для обработки текстов могут быть объекты Application, Document и Toolbar.

Чтобы создать ActiveX, назначьте объекту CreateObject объекту, объектная переменная:

Примечание: В примерах ниже показано, как использовать эту функцию в модуле Visual Basic для приложений (VBA). Чтобы получить дополнительные сведения о работе с VBA, выберите Справочник разработчика в раскрывающемся списке рядом с полем Поиск и введите одно или несколько слов в поле поиска.

' Declare an object variable to hold the object 
' reference. Dim as Object causes late binding.
Dim ExcelSheet As Object
Set ExcelSheet = CreateObject("Excel.Sheet")

В этом примере мы автоматиз будем автоматизировать объект электронной таблицы Excel из базы данных Access. Этот код запускает приложение, созда которое создает объект, в данном случае таблицу Microsoft Excel. На созданный объект можно ссылаться в коде с помощью определенной вами объектной переменной. В следующем примере доступ к свойствам и методам нового объекта осуществлялся с помощью объектной переменной, ExcelSheet и других объектов Excel, включая объект Application и коллекцию Cells.

' Make Excel visible through the Application object.
ExcelSheet.Application.Visible = True
' Place some text in the first cell of the sheet.
ExcelSheet.Application.Cells(1, 1).Value = "This is column A, row 1"
' Save the sheet to C:test.xls directory.
ExcelSheet.SaveAs "C:TEST.XLS"
' Close Excel with the Quit method on the Application object.
ExcelSheet.Application.Quit
' Release the object variable.
Set ExcelSheet = Nothing

При объявлении объектной переменной с помощью предложения As Object создается переменная, которая может содержать ссылку на любой тип объекта. Однако обращение к объекту через эту переменную выполняется с поздним связыванием, то есть привязка создается при выполнении программы. Чтобы создать объектную переменную с ранним связыванием, то есть со связыванием при компиляции программы, объявите объектную переменную с определенным идентификатором класса. Например, объявите и создайте следующие ссылки Excel:

Dim xlApp As Excel.Application 
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.WorkSheet
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)

С помощью ссылки на ранняя переменная можно улучшить производительность, но она может содержать только ссылку на класс, заданную в объявление.

Можно передать объект, возвращаемый функцией CreateObject, функции, которая использует объект в качестве аргумента. Например, в следующем коде создается и передается ссылка на объект Excel.Application:

Call MySub (CreateObject(«Excel.Application»))

Вы можете создать объект на удаленном компьютере, подключенном к сети, указав его имя в аргументе имя_сервера функции CreateObject. Это имя совпадает с именем компьютера в имени общего ресурса: для имени «\MyServerPublic» имя_сервера будет «MyServer».

Примечание:  Дополнительные сведения о том, как сделать приложение видимым на удаленном сетевом компьютере, см. в документации COM (Microsoft Developer Network). Возможно, понадобится добавить раздел реестра для приложения.

Следующий код возвращает номер версии экземпляра приложения Excel, запущенного на удаленном компьютере с именем MyServer:

Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application", "MyServer")
Debug.Print xlApp.Version

Если удаленный сервер не существует или недоступен, возникает ошибка во время выполнения.

Примечание:  Используйте функцию CreateObject, если текущий экземпляр объекта отсутствует. Если экземпляр объекта уже запущен, запускается новый экземпляр и создается объект указанного типа. Чтобы использовать текущий экземпляр или запустить приложение и загрузить файл, следует воспользоваться функцией GetObject.

Если объект зарегистрировал себя как объект типа «единственный экземпляр», создается только один экземпляр этого объекта независимо от того, сколько раз выполнялась функция CreateObject.

Пример

В данном примере функция CreateObject используется для задания ссылки (

xlApp

) в Excel. Ссылка используется для доступа к свойству «Видимый» в Excel, а затем используется метод выхода Excel, чтобы закрыть его. Наконец, выпустится сама ссылка.

Dim xlApp As Object    ' Declare variable to hold the reference.
Set xlApp = CreateObject("excel.application")
' You may have to set Visible property to True
' if you want to see the application.
xlApp.Visible = True
' Use xlApp to access Microsoft Excel's
' other objects.
xlApp.Quit ' When you finish, use the Quit method to close
Set xlApp = Nothing ' the application, then release the reference.

Нужна дополнительная помощь?

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
  • Remove From My Forums
  • Question

  • I’m currently trying to use a module in Access 2010 to open an Excel file and write to specific fields within said file. I have attempted this multiple times from many approaches with little avail. I added a reference to «Microsoft Excel 14.0 Object
    Library» and I am trying to do this currently:

    Dim xlsxApplication As Object
      
    'Open the Excel application
    xlsxApplication = CreateObject("Excel.Application")
    

    The current error I am recieving is Run-time error ’91’: Object variable or With block variable not set

    I have also attempted something like this:

    Dim xlsxApplication As Excel.Application
      
    'Open the Excel application
    xlsxApplication = New Excel.Application
    

    Does anyone know the correct way to go about this?


    One must therefore be a fox to recognize traps, and a lion to frighten wolves.

Answers

  • I needed to add a Set. My bad

    Dim xlsxApplication As
    Object

     
    ‘Open the Excel application
    Set xlsxApplication = CreateObject(«Excel.Application»)


    One must therefore be a fox to recognize traps, and a lion to frighten wolves.

    • Marked as answer by

      Monday, May 9, 2011 3:33 PM

Base on Matt Hall’s answer but altered to show how you can, from Access:

  • Invoke an Excel module apart from ThisWorkbook;
  • Invoke Excel Subs or retrieve a value from an Excel Function; and
  • Fetch the atlered values of parameters passed by reference.

In a custom module, named basTextModule, in Excel:

Public Sub ShowCoolMessage()
 MsgBox "cool"
End Sub

' Add02 is explictly ByRef (the default in VBA) to show that
' the parameter will be altered and have its value changed even for
' prodedures higher up the call stack.
Public Function GetCoolAmount(Add01 As Variant, _
                            Optional ByRef Add02 As Integer) As Integer
  Add02 = Add02 + 1
  GetCoolAmount = 10 + Add01 + Add02
End Function

In Access:

  • Set a reference to Excel (VBA IDE > Tools > Reference … Microsoft Excel 16.0 Object Library).
  • Then create a (somewhat) generic RunExcelCode …

For parameters passed by reference to work:

  • Note from Microsoft Docs, Application.Run method (Excel) that when you pass parameters to the Excel Sub or Function «You cannot use named arguments with this method. Arguments must be passed by position».

  • When declaring excelApp use Object rather than Excel.Application in order to ensure that the value of any parameters passed by reference to excelApp.Run can be retrieved. Source: Jaafar Tribak «Application.Run .. (Argument Passed ByRef)» at https://www.mrexcel.com/board/threads/application-run-argument-passed-byref.998132/post-4790961

  • In the called sub or Function the parameters (apart from the first ModuleAndSubOrFunctionName) must have a data type that match the datatype of the parmaters for the calling module or function. They can be variants or a specific datatype. E.g, and for illustrative purposes, Arg02 is an Integer and so must the second argument of GetCoolAmount when RunExcelCode(WorkbookPathAndFileName, "basTestModule.GetCoolAmount" ...) is used.

    However to make your RunExcelCode more generic it may be wise to ensure Arg01, Arg02, … Arg30 paramters are all variants; and therefore the parameters of your ultimately called sub or function are also variants, for example …

    Public Function GetCoolAmount(Add01 As Variant, _
                              Optional ByRef Add02 As Variant) As Integer
    ...
    
Public Function RunExcelCode(WorkbookPathAndFileName As String, _
                             ModuleAndSubOrFunctionName As String, _
                             Optional ByRef Arg01 As Variant, _
                             Optional ByRef Arg02 As Integer) As Variant
  ' Must be Object, not Excel.Application, to allow for parameters pass by reference
  Dim excelApp  As Object
  Dim workbook  As Excel.workbook
  
  Dim Result As Variant
  
On Error GoTo HandleErr
  
  ' Can be Excel.Application if excelApp previously declared as Object
  Set excelApp = New Excel.Application
  
'  excelApp.Visible = True ' For debugging
  
  Set workbook = excelApp.Workbooks.Open(WorkbookPathAndFileName)
  
  ' Get a value from a function or,
  ' if it is a sub a zero length string "" will be returned
  Result = excelApp.Run(ModuleAndSubOrFunctionName, Arg01, Arg02)
  
  RunExcelCode = Result

ExitHere:
  workbook.Close
  excelApp.Quit
  Set workbook = Nothing
  Set excelApp = Nothing
Exit Function

HandleErr:
  Select Case Err.number
    Case Else
      MsgBox "Error " & Err.number & ": " & Err.Description, _
        vbCritical, "RunExcelCode"
  End Select
  Resume ExitHere
End Function

Testing (from Access), calling a Sub and a Function:

Private Sub TestRunExcelCode()
  Dim WorkbookPathAndFileName  As String
  Dim Result As Variant
  
  WorkbookPathAndFileName = "C:UsersYourNameDocumentsMyWorkbook.xlsm"
  
  '   Run a sub
  Result = RunExcelCode(WorkbookPathAndFileName, "basTestModule.ShowCoolMessage")
  If IsNull(Result) Then
    Debug.Print "{Null}"
  ElseIf Result = "" Then
    Debug.Print "{Zero length string}"
  Else
    Debug.Print Result
  End If

  ' Will output "{Zero length string}"
  
  ' Get a value from a function
  Dim Arg02 As Integer
  Arg02 = 1
  Debug.Print "Arg02 Before: " & Arg02
  Result = RunExcelCode(WorkbookPathAndFileName, _
                      "basTestModule.GetCoolAmount", 1, Arg02)
  Debug.Print "Arg02 After : " & Arg02  ' Value will have changed, as desired.
  Debug.Print "Result      : " & Result
  
End Sub

Edit 01: Major change to make code more generic.

Edit 02: Major change to handle paramaters passed by reference.

Edit 03: Added details in the case «to make your RunExcelCode more generic».

Открытие книги Excel через Access

A_3485

Дата: Пятница, 05.10.2012, 10:59 |
Сообщение № 1

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 146


Репутация:

0

±

Замечаний:
40% ±


2007

Доброе утро!
Помогите пожалуйста разобраться с кодом, который написа в Access. При нажатии на кнопку на форме Access, у меня открываетя книга excel, а вот потом все неработает, не могу понять почему….

[vba]

Code

Dim oXL As Object
     Dim sFullPath As String
     Set oXL = CreateObject(«Excel.Application»)
     On Error Resume Next
     oXL.UserControl = True
     On Error GoTo 0          
          On Error GoTo ErrHandle
     sFullPath = «C:Documents and Settingsзаявление.xls»                
     With oXL
         .Visible = True
         .Workbooks.Open (sFullPath)
         .Workbooks(«sFullPath»).Activate
         .ThisWorkbook.Unprotect Password:=»555″
         .Sheets(«Лист1»).Visible = False
         .Sheets(«Лист2»).Visible = False         
     End With      
ErrExit:
     Set oXL = Nothing
     Exit Sub      
ErrHandle:
     oXL.Visible = False
     MsgBox Err.Description
     GoTo ErrExit
End Sub

[/vba]

 

Ответить

Pelena

Дата: Пятница, 05.10.2012, 13:28 |
Сообщение № 2

Группа: Админы

Ранг: Местный житель

Сообщений: 18797


Репутация:

4284

±

Замечаний:
±


Excel 2016 & Mac Excel

Эта строчка неправильная, без неё нормально открывается
.Workbooks(«sFullPath»).Activate

ИМХО: с обработчиками ошибок перемудрили


«Черт возьми, Холмс! Но как??!!»
Ю-money 41001765434816

 

Ответить

A_3485

Дата: Пятница, 05.10.2012, 14:34 |
Сообщение № 3

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 146


Репутация:

0

±

Замечаний:
40% ±


2007

Да это так, но мне нужно, чтобы Книга стала активной и отобразился Лист1

 

Ответить

Pelena

Дата: Пятница, 05.10.2012, 14:38 |
Сообщение № 4

Группа: Админы

Ранг: Местный житель

Сообщений: 18797


Репутация:

4284

±

Замечаний:
±


Excel 2016 & Mac Excel

Quote (A_3485)

чтобы Книга стала активной и отобразился Лист1

Как же он отобразится, если вы его в этом коде скрываете?


«Черт возьми, Холмс! Но как??!!»
Ю-money 41001765434816

 

Ответить

A_3485

Дата: Пятница, 05.10.2012, 15:37 |
Сообщение № 5

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 146


Репутация:

0

±

Замечаний:
40% ±


2007

Я наверное не совсем правильно выразился в постановке задачи. Мне хтелось бы, чтобы после пыполнения указанного кода, стал активен excel, т.е автоматически произошло переключение на активную книгу.

 

Ответить

Gustav

Дата: Пятница, 05.10.2012, 16:32 |
Сообщение № 6

Группа: Друзья

Ранг: Старожил

Сообщений: 2397


Репутация:

985

±

Замечаний:
0% ±


начинал с Excel 4.0, видел 2.1

Поскольку при помощи CreateObject(«Excel.Application») создается новый экземпляр (сессия) Excel (в отличие от GetObject), то открываемая книга будет в нём единственная, а, значит, и активная. Поэтому дополнительно ее активировать не надо (тем более таким ошибочным оператором).


МОИ: Ник, Tip box: 41001663842605

 

Ответить

A_3485

Дата: Пятница, 05.10.2012, 16:40 |
Сообщение № 7

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 146


Репутация:

0

±

Замечаний:
40% ±


2007

Спасибо, буду исправлять. А как можно упростить код?

 

Ответить

Pelena

Дата: Пятница, 05.10.2012, 16:58 |
Сообщение № 8

Группа: Админы

Ранг: Местный житель

Сообщений: 18797


Репутация:

4284

±

Замечаний:
±


Excel 2016 & Mac Excel

По мне так вот такой код вполне может открыть нужный файл на первом листе
[vba]

Code

    Dim oXL As Object
     Set oXL = CreateObject(«Excel.Application»)
     With oXL
         .Workbooks.Open «C:Documents and Settingsзаявление.xls»
         .Visible = True
     End With
     Set oXL = Nothing

[/vba]


«Черт возьми, Холмс! Но как??!!»
Ю-money 41001765434816

 

Ответить

A_3485

Дата: Пятница, 05.10.2012, 17:16 |
Сообщение № 9

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 146


Репутация:

0

±

Замечаний:
40% ±


2007

Все бы ничего если бы…..открывался именно файл «заявление» не как файл для чтения(при сохранения пишет замеить существующий), а сам по себе и при открытии можно было снять пароли, отобразить Листы, и сделать книгу активной.

 

Ответить

Gustav

Дата: Пятница, 05.10.2012, 17:27 |
Сообщение № 10

Группа: Друзья

Ранг: Старожил

Сообщений: 2397


Репутация:

985

±

Замечаний:
0% ±


начинал с Excel 4.0, видел 2.1

Может, Вам лучше будет открыть как шаблон, т.е. не через Open, а через Add ?

[vba]

Code

        .Workbooks.Add «C:Documents and Settingsзаявление.xls»

[/vba]


МОИ: Ник, Tip box: 41001663842605

Сообщение отредактировал GustavПятница, 05.10.2012, 17:29

 

Ответить

Pelena

Дата: Пятница, 05.10.2012, 17:29 |
Сообщение № 11

Группа: Админы

Ранг: Местный житель

Сообщений: 18797


Репутация:

4284

±

Замечаний:
±


Excel 2016 & Mac Excel

Я, конечно, не вижу Ваш файл. Создала свой. Но у меня он открывается с возможностью редактирования и сохраняется обычным образом.

Может Вы несколько раз уже эту кнопку нажали, и файл уже был открыт, тогда, конечно, ТОЛЬКО ДЛЯ ЧТЕНИЯ


«Черт возьми, Холмс! Но как??!!»
Ю-money 41001765434816

 

Ответить

Hugo

Дата: Пятница, 05.10.2012, 23:37 |
Сообщение № 12

Группа: Друзья

Ранг: Участник клуба

Сообщений: 3140


Репутация:

670

±

Замечаний:
0% ±


2010, теперь уже с PQ

Вероятно файл уже открыт в другом экземпляре Экселя — поэтому все остальные экземпляры открывают для чтения.
Есть способ открыть в уже открытом экселе, или если его нет — тогда открыть в новом.
Вот например — скрипт vbs (в соответствии с темой smile ), но синтаксис в общем одинаков:
[vba]

Code

Option Explicit
Dim objFSO, objExcel, ExcelPath, wb

ActivateExcel

Set objFSO = CreateObject(«Scripting.FileSystemObject»)   
ExcelPath = objFSO.GetParentFolderName(WScript.ScriptFullName)   
Set wb = objExcel.Workbooks.Open (ExcelPath & «test.xls»)
Set objExcel = Nothing

Private Function ActivateExcel()
On Error resume next   
Set objExcel = GetObject(, «Excel.Application»)
If objExcel Is Nothing Then
   Set objExcel = CreateObject(«Excel.Application»)
   objExcel.Visible = True
End If
End Function

[/vba]


excel@nxt.ru
webmoney: R418926282008 Z422237915069

 

Ответить

A_3485

Дата: Суббота, 06.10.2012, 16:51 |
Сообщение № 13

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 146


Репутация:

0

±

Замечаний:
40% ±


2007

Спасибо всем что откликнулись на мою просьбу!
У меня теперь стоит задача, чтобы в коде VBA который пишется в Access, можно было снять защиту с листа «1111» и книги «1111» и активировать «Лист1»?

 

Ответить

Pelena

Дата: Суббота, 06.10.2012, 18:46 |
Сообщение № 14

Группа: Админы

Ранг: Местный житель

Сообщений: 18797


Репутация:

4284

±

Замечаний:
±


Excel 2016 & Mac Excel

Я в макросах не специалист, но можно попробовать, например, так
[vba]

Code

Dim oXL As Object
     Set oXL = CreateObject(«Excel.Application»)
     With oXL
         .Workbooks.Open «C:Documents and Settings1111.xls»
         .Visible = True
         .Sheets(«1111″).Unprotect Password:=»555»
         .Sheets(«Лист1»).Activate
         .ActiveWorkbook.Unprotect Password:=»555″
     End With
     Set oXL = Nothing

[/vba]


«Черт возьми, Холмс! Но как??!!»
Ю-money 41001765434816

 

Ответить

A_3485

Дата: Воскресенье, 07.10.2012, 10:51 |
Сообщение № 15

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 146


Репутация:

0

±

Замечаний:
40% ±


2007

Спасибо помогло!! А что означает строчка:
[vba][/vba]

 

Ответить

Gustav

Дата: Воскресенье, 07.10.2012, 19:40 |
Сообщение № 16

Группа: Друзья

Ранг: Старожил

Сообщений: 2397


Репутация:

985

±

Замечаний:
0% ±


начинал с Excel 4.0, видел 2.1

Quote (A_3485)

А что означает строчка:

Set oXL = Nothing

Ответ, например, здесь: http://www.askit.ru/custom/vba_office/m4/04_02_objects_creation.htm

Quote

Удаление объектов производится очень просто:

Set объектная_переменная = nothing

например,

Set oApp = nothing

В принципе, объект можно и не удалять — он будет удален автоматически после того, как последняя объектная переменная, которая на него ссылается, уйдет за область видимости (обычно это значит, что закончит работу процедура, в которой он используется). Однако явное удаление объектов — это «правило хорошего тона», которое позволит вам при создании серьезных приложений избежать конфликтов имен и перерасхода ресурсов.


МОИ: Ник, Tip box: 41001663842605

 

Ответить

A_3485

Дата: Воскресенье, 07.10.2012, 22:06 |
Сообщение № 17

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 146


Репутация:

0

±

Замечаний:
40% ±


2007

Всем спасибо! Все получилось. Можно тему закрывать.

 

Ответить

Понравилась статья? Поделить с друзьями:
  • Access not importing excel file
  • Access meaning of the word
  • Access keys in excel
  • Access import from excel vba
  • Access help in word