繁体   English   中英

从 Access 将变量分配给打开的 Excel 工作簿

[英]Assign a variable to an opened Excel workbook from Access

我正在使用 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 文件的完整路径。 然后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 实例。

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

Set g_xl = CreateObject("Excel.Application")

或者

Set g_xl = GetObject("Excel.Application")

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM