I am working on an Access database with VBA, which needs to obtain data from an Excel workbook.
I need to assign a variable to the open book (set g_xl =????) without opening another Excel instance (appoint to opened workbook).
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
You don't need any of this, only the full path to the Excel file. Then GetObject()
can get a reference to the open workbook.
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
This will only start a new Excel instance, if the file isn't open.
With g_xl as type Excel.Application
, that commented line is going to be
Set g_xl = CreateObject("Excel.Application")
or
Set g_xl = GetObject("Excel.Application")
The latter will hook up with an existing Excel.Application
which is what I think you're trying to do. It will create a new instance if an existing one isn't found.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.