mgae2m
mgae2m

Reputation: 1142

ThisDocument object reference

How ThisDocument object refers to the docm file contents, which containing the code?

I had insert a module under the *.docm project which contains this code:

Sub test()
   Debug.Print ThisDocument.Name
End Sub

Returns Normal.dotm as result.

But it is expected returning the current docm file's name.

How can set 'Thisdocument' Object subroutines refers to the current docm file?

Any help would be greatly appreciated.

Upvotes: 1

Views: 2205

Answers (2)

Ahmed AU
Ahmed AU

Reputation: 2777

As commented by Cindy Meister, From the tagging and the question it's not clear exactly what you have (or have in your mind). However assuming that you are aiming something highly tricky and unconventional with both Excel & Word applications involved. In normal condition ThisDocument will never refer to Normal.dotm(from a module under the *.xlsm project) but since you made it happen and also aim to "set Thisdocument Object refers to the current xlsm file", I would have try it like this from a module in xlsm file.

Global ThisDocument As Object
Sub calltest()
Dim wd As Word.Application
Set wd = CreateObject("Word.Application")
wd.Visible = True                 'for demo only
Set ThisDocument = wd.Templates(1)   'This will result Normal.dotm (as you are experiencing - may be similar code is already in the calling routine)
test
Set ThisDocument = ThisWorkbook     'This will result workbook Containing the module with code
test
End Sub
Sub test()
Debug.Print ThisDocument.Name
End Sub

Obviously it is assumed Reference to Microsoft Word XX Object Library had aleady been taken.

Upvotes: 1

Jenn
Jenn

Reputation: 647

Get the name of the Excel file which contains the code you are running:

ThisWorkbook.Name

Get the name of the Excel file that your code is currently referencing:

ActiveWorkbook.Name

If you are running code from a Word doc that is referencing an Excel file, you would use ActiveWorkbook.Name.

This post goes into more detail on ActiveWorkbook vs ThisWorkbook. Difference between Thisworkbook.name and Activeworkbook.name in VBA

Upvotes: 1

Related Questions