【问题标题】:Assign a variable to an opened Excel workbook from Access将变量分配给从 Access 中打开的 Excel 工作簿
【发布时间】:2019-11-20 09:54:34
【问题描述】:

我正在使用 VBA 处理 Access 数据库,它需要从 Excel 工作簿中获取数据。

我需要为打开的书分配一个变量(设置 g_xl = ????)而不打开另一个 Excel 实例(指定打开的工作簿)。

Sub AssignVariableToExcelApplication()
    Dim g_xl As Excel.Application
    Dim strComputer As String
    Dim objWMIService As Object
    Dim colitems As Object
    Dim objitem As Object

    strComputer = "."
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
    Set colitems = objWMIService.ExecQuery("SELECT * FROM Win32_Process", , 48)

    Dim row As Integer
    row = 1
    For Each objitem In colitems
        If objitem.Name = "EXCEL.EXE" Then
            Debug.Print objitem.ProcessID & vbCrLf & _
                        objitem.Name & vbCrLf & _
                        objitem.Caption & vbCrLf & _
                        objitem.CommandLine & vbCrLf & _
                        objitem.ExecutablePath

            'This is the question
            'Set g_xl = objitem ?????? (I need that g_xl appoints to objitem)
            Exit For
        End If
    Next
End Sub

【问题讨论】:

    标签: excel vba ms-access


    【解决方案1】:

    您不需要任何这些,只需要 Excel 文件的完整路径。然后GetObject() 可以获得对打开的工作簿的引用。

    sPath = "C:\my\path\myWorkbook.xlsx"
    Set wb = GetObject(sPath)
    ' Demo
    Debug.Print wb.Sheets(1).Cells(1,1).Value
    ' If you need the Application
    Set g_xl = wb.Application
    

    如果文件未打开,这只会启动一个新的 Excel 实例。

    【讨论】:

      【解决方案2】:

      使用 g_xl 作为类型 Excel.Application,注释行将是

      Set g_xl = CreateObject("Excel.Application")
      

      Set g_xl = GetObject("Excel.Application")
      

      后者将与现有的Excel.Application 挂钩,我认为您正在尝试这样做。如果找不到现有实例,它将创建一个新实例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-29
        • 1970-01-01
        • 1970-01-01
        • 2014-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多