Here is a little .Net app that shows how you can get hold of an excel instance so that you can use that Excel object from code – but with out using IDT. This is useful when writing classes rather than managed addins. I will hopefully make a post about how we can use .net classes from VBA in a little bit, but this is worth a post in it’s own right.
here is the example app
Know, the most interesting method here is the bind to moniker one as that lets us get the application that a particular file is active in, and so give use the most certainty that we are targeting the Excel instance we wish to. I have stuck this into a function:
[vbnet]
Imports System.Runtime.InteropServices
Imports xl = excel.application
”’Class for Getting an Excel Intance
Public Class GetExcelInstance
Public Function GetTargetXLApplication(ByVal sPassedFilePath As String) As Excel.Application
Dim sFilePath As String = sPassedFilePath
Dim wkbBindToBook As Excel.Workbook
Dim blXLBelongsToUs As Boolean ”FLAG FOR KILLING XL APP LATER
Dim cFiles As System.IO.FileInfo
Dim sWkbName As String
”get filename from path
cFiles = My.Computer.FileSystem.GetFileInfo(sFilePath)
sWkbName = cFiles.Name
Try
”Set our target wkb from the file path to our
”.net wkb ojbect dimed here
wkbBindToBook = Marshal.BindToMoniker(sFilePath)
”set the appliction referance to the host excel sever this workbook is running in
GetTargetXLApplication = wkbBindToBook.Application
”the following code manipulates the excel clients window state.
If GetTargetXLApplication.Visible = False Then
”we opened excel
GetTargetXLApplication.Visible = True
GetTargetXLApplication.Windows(sWkbName).Visible = True
blXLBelongsToUs = False ”FLAG FOR QUITING IF WE STARTED IT
‘ MsgBox(“Moniker from no intance”) ”for debug
Else
”excel was opened but we loaded a hidden file into it, lets make it visable
If GetTargetXLApplication.Windows(sWkbName).Visible = False Then
GetTargetXLApplication.Windows(sWkbName).Visible = True
‘ MsgBox(“Moniker from existing intance”) ”for debug
End If
‘ MsgBox(“Moniker from existing intance”) ”for debug
End If
Catch ex As Exception
MsgBox(ex.Message)
GetTargetXLApplication = nothing ‘sets function to null object if error happen
End Try
End Function
[/vbnet]
The VS project files are here
Did anybody noticed that code
GetTargetXLApplication.Windows(sWkbName).Visible = True
makes wkbBindToBook.Saved to true?
Hi Lava, no I did not notice this, does it cause a problem?
thanks
Ross