How do you retrieve a pointer to the active workbo

2019-09-12 15:09发布

问题:

I am new to VB.net and am moving an app from VBA. I want to use the document customization model, but can't for the life of me find a way to retreive a pointer to the workbook that is hosting the customization. I have tried

dim wb as workbook = Me.Workbook
dim wb as workbook = thisWorkBook
dim wb as workbook = ThisApplication.workbook 

etc. I only need this in order to be able to select worksheets in the customization so if there is anotherway to do that then that would answer my question too. For example I want to execute this to get a handle to a specific worksheet.

dim ws as worksheet = wb.sheets("My Sheet Name")

Apologies for what is clearly a very basic question but I have googled around for about three hours so far with no luck.

回答1:

After a lot of additional trial and error I came across this solution.

You can access the application workbook through the Globals variable produced by VSTO. Thus,outside of the class declaration for thisWorkbook -- the following will work:

Dim wb as ThisWorkBook
wb = Globals.ThisWorkbook

Note that web is not of type Workbook but ThisWorkBook which is an overloaded class defined by Visual Studio in the document customization template.