Macros blocked while testing Add-In + C# Documents.Open() question

Comfrog
NewLounger
Posts: 6
Joined: 11 Jul 2023, 19:04

Macros blocked while testing Add-In + C# Documents.Open() question

Post by Comfrog »

Word 365 / C# VSTO Word Add-in;

Hello there,

I'm new here, so I'm not sure if this is the correct place to create this post, but I am having some troubles with a C# VSTO Word add-in I am creating. Apologies if I get some terminology mixed up, as I am fairly new to development within the Microsoft Office Suite and new to the advanced parts of Word as a whole apart from using it for writing essays years ago.

I am attempting to figure out a way that I can open a document so I can do some repeated functions on autotextentries, which might be relevant to the question, or it might not I suppose.

I can do everything correctly in the VBA editor within Word for what I'd like to achieve, but when I rewrite the code within a VSTO Add-In (I'd like it to be an add-in opposed to just having the code in a template stored in normal), I get a plethora of problems. The first problem is that when editing the template of a document, which I retrieve using Application.Documents.Open("filepath here") within the VBA editor in Word correctly opens files in their full read/write mode. But, when I use the exact same function within Microsoft.Office.Interop.Word, it only opens the document with the convert document popup window, and no matter what selection I use (the "create a copy and merge later" option is realistically the only usable option), the add-in hangs and the function does not proceed. Read-only is not going to work, as I need to be able to edit the building blocks of the file that I am trying to open.
Now today, when I try to run the add-in on testing, I no longer get past a macros blocked window that the macro is unsafe. However, the macro is a .tmp file within C:\Users\Comfrog\AppData\Local\Microsoft\Windows\INetCache\Content.Word.
I have 2 questions which hopefully someone can give me some sort of a guiding question towards an answer since I am stumped and have been for awhile:

1. Since I am plagued with the macro error and can't get past it for a random reason starting yesterday, with nothing changed on my pc to point towards a cause for this, is there a way I can add the filepath ~\AppData\Local\Microsoft\Windows\INetCache\Content.Word to the trusted locations even though it's a protected system folder? Or is there some way I can just allow all macros no matter what? I have trust center all setup in every way possible to accept literally everything, akin to turning off an antivirus just for the sake of development for this add-in,

2. Is there any possible way to open a document the same way you can use Application.Documents.Open() within the VBA code editor, which just simply opens documents with no popups or required selections (read-only, create a copy), or will I have to resort to the backdoor route of creating a copy of the document+template and then editing it all in one go?

I can post the code if needed.

User avatar
HansV
Administrator
Posts: 78524
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Macros blocked while testing Add-In + C# Documents.Open() question

Post by HansV »

Welcome to Eileen's Lounge!

I hope we have someone with experience in C# on board.
Best wishes,
Hans

robertocm
Lounger
Posts: 43
Joined: 07 Jun 2023, 15:34

Re: Macros blocked while testing Add-In + C# Documents.Open() question

Post by robertocm »

I am attempting to figure out a way that I can open a document so I can do some repeated functions on autotextentries
I would try COM automation from a script similar to this example posted in the AutoIt forum

I use this VBA code in a word document that could give you some ideas:

Code: Select all

Public Sub UpdateBookmark(oDoc As Document, BookmarkToUpdate As String, ByVal TextToUse As String)
'This procedure set forth by Dave Rado at http://www.mvps.org/word/FAQs/MacrosVBA/InsertingTextAtBookmark.htm
'https://stackoverflow.com/questions/25026969/alternative-to-activedocument-to-refer-to-new-document-from-a-template
Dim BMRange As Range
Set BMRange = oDoc.Bookmarks(BookmarkToUpdate).Range
BMRange.text = TextToUse
oDoc.Bookmarks.Add BookmarkToUpdate, BMRange
End Sub

Sub Test_Bookmark_inside_table()
Dim oDoc As Document, DocumentBodyTable As Table, rng As Range, BMRange As Range, BookmarkToUpdate As String, BookmarkToUpdate_2 As String, TextToUse As String, j As Integer
Set oDoc = ThisDocument
Set DocumentBodyTable = oDoc.Tables(1)
Set rng = DocumentBodyTable.Rows(2).Cells(2).Range
j = 1

rng.text = "Alb: "
rng.Collapse Direction:=wdCollapseEnd
rng.MoveEnd Unit:=wdCharacter, Count:=-1

BookmarkToUpdate = "CodAlb_" & j
TextToUse = "0000005"
oDoc.Bookmarks.Add BookmarkToUpdate, rng
UpdateBookmark oDoc, BookmarkToUpdate, TextToUse

'oDoc.Bookmarks(BookmarkToUpdate).Range.InsertAfter (" Fecha ")
Set rng = DocumentBodyTable.Rows(2).Cells(2).Range
rng.Collapse Direction:=wdCollapseEnd
rng.MoveEnd Unit:=wdCharacter, Count:=-1
rng.text = " Fecha: "

rng.Collapse Direction:=wdCollapseEnd

BookmarkToUpdate_2 = "FeAlb_" & j
TextToUse = "07/09/2022"
oDoc.Bookmarks.Add BookmarkToUpdate_2, rng
UpdateBookmark oDoc, BookmarkToUpdate_2, TextToUse

Set BMRange = oDoc.Bookmarks(BookmarkToUpdate).Range
BMRange.Style = "Consolas9"
Set BMRange = oDoc.Bookmarks(BookmarkToUpdate_2).Range
BMRange.Style = "Consolas9"

'DocumentBodyTable.Cell(2, 2).Range.Text = "| "
'If Left(rng.Text, 2) = "| " Then
'    ' Change range to first two characters and delete them. '
'    rng.Collapse Direction:=wdCollapseStart
'    rng.MoveEnd Unit:=wdCharacter, Count:=2
'    rng.Delete
'Else
'    ' Just insert the vertical bar. '
'    rng.InsertBefore ("| ")
'End If

'Fonte: VBA Help MoveEnd
'If ActiveDocument.Words.Count >= 3 Then
'    Set myRange = ActiveDocument.Words(2)
'    With myRange
'        .MoveEnd Unit:=wdWord, Count:=1
'        .Select
'    End With
'End If

'Fonte: VBA Help Text
'For i = 1 To 10
'    Selection.Text = "Line" & Str(i) & Chr(13)
'    Selection.MoveDown Unit:=wdParagraph, Count:=1
'Next i
End Sub

Sub Test_Clear_Bookmark()
Dim oDoc As Document
Set oDoc = ThisDocument
UpdateBookmark oDoc, "TipRE4", " "
UpdateBookmark oDoc, "CuotaRE4", " "
End Sub

snb
4StarLounger
Posts: 582
Joined: 14 Nov 2012, 16:06

Re: Macros blocked while testing Add-In + C# Documents.Open() question

Post by snb »

I'd like it to be an add-in opposed to just having the code in a template stored in normal)
You can create a .dotm file, store it in the addins directory and load it via the Developer Tab/ AddIns.
I can't see any benefit doing otherwise.

robertocm
Lounger
Posts: 43
Joined: 07 Jun 2023, 15:34

Re: Macros blocked while testing Add-In + C# Documents.Open() question

Post by robertocm »

I can't see any benefit doing otherwise.
i suggested the external script from my experience of sending invoices to clients from a .dotm file:

Windows scheduled task runs the script having code to bypass the .dotm file AutoOpen macro (see attachment), and then executing the invoice query, editing bookmarks and export to .pdf. The same script send the new invoices to clients by email as attachments.

invoice_template.docm

User avatar
Charles Kenyon
5StarLounger
Posts: 620
Joined: 10 Jan 2016, 15:56
Location: Madison, Wisconsin

Re: Macros blocked while testing Add-In + C# Documents.Open() question

Post by Charles Kenyon »

snb wrote:
12 Jul 2023, 09:04
I'd like it to be an add-in opposed to just having the code in a template stored in normal)
You can create a .dotm file, store it in the addins directory and load it via the Developer Tab/ AddIns.
I can't see any benefit doing otherwise.
If stored in the Word Startup folder, the file will load as a template add-in automatically.
https://addbalance.com/word/startup.htm#PageStart

Comfrog
NewLounger
Posts: 6
Joined: 11 Jul 2023, 19:04

Re: Macros blocked while testing Add-In + C# Documents.Open() question

Post by Comfrog »

Thanks for the replies.
robertocm wrote:
12 Jul 2023, 06:46
I would try COM automation from a script similar to this example posted in the AutoIt forum
So you'd use autohotkey/autoit to open the file instead of the built in function correct? While I do appreciate this solution as I assume it might solve the problem I am having with the opening of the document in read/write, I need this to be a built-in solution. A third party script to open the document shouldn't be the way to solve this problem (in this specific case where it's not for a client and I cannot do the install myself to make it easier for them) when I can just simply add a document to the current open documents via Application.Documents.Open() with the param for the window being hidden, and then perform actions on the autotextentries. This function completely works when the code is written within the .dotm file, but when I transfer it to a VSTO add-in 1:1 code-wise, it completely breaks. The document opens, but there isn't enough trust between the add-in and word to open the file with all permissions I guess. Everything needs to be bundled into one add-in. If I am wrong about this though and didn't understand your solution, apologies!
snb wrote:
12 Jul 2023, 09:04
You can create a .dotm file, store it in the addins directory and load it via the Developer Tab/ AddIns.
I can't see any benefit doing otherwise.
Charles Kenyon wrote:
12 Jul 2023, 13:58
If stored in the Word Startup folder, the file will load as a template add-in automatically.
https://addbalance.com/word/startup.htm#PageStart
I appreciate this response because it does confirm my initial thoughts about the solution to this problem. The reason that I want this to be an add-in, is so I can offer the add-in to third parties in an easy-to-install fashion. If this was for a client, I'd have no problem with the installation being this way, but it's more for creating a toolkit of sorts as a product. Offering this functionality as well as bundling in other things into the add-in seems to be the best course of action, however I am coming to terms with Word's add-in limitations.
I did originally have the realization that the easiest and not-overly-convoluted-100-hour-research-and-development-way to complete this task was to simply just offer all the functionality within a .dotm file and offer a readme on how to install it instead, which offers the perfect solution to my problem. The code within a .dotm does indeed open the document, and I can work with the autotextentries the way that I'd like without trying to figure out the weirdest workaround to exist (running a script to open a file; creating copies of the file and saving a new copy, introducing intermediate steps to solve the problem).

Unfortunately, I think that my options are very limited since C# add-in development seems to not be all that popular from my (extensive) searches around google/youtube. I suppose I could try the VB implementation to see if that changes anything, but I think it's their solution to security.
I understand from a Software Engineering point that some problems can only be solved in a torturously complex way, but this one is one I don't think is possible, and I might have to compromise with Microsoft and store it in a .dotm file as snb/Charles stated. :shrug:

robertocm
Lounger
Posts: 43
Joined: 07 Jun 2023, 15:34

Re: Macros blocked while testing Add-In + C# Documents.Open() question

Post by robertocm »

If you only need to update data, perhaps this could be an option:
Custom XML parts overview
How to: Add custom XML parts to document-level customizations

User avatar
Charles Kenyon
5StarLounger
Posts: 620
Joined: 10 Jan 2016, 15:56
Location: Madison, Wisconsin

Re: Macros blocked while testing Add-In + C# Documents.Open() question

Post by Charles Kenyon »

I have a number of Add-Ins on my site that contain macros to self-install. They detect the Startup Folder and then save there.
Some simply have a macro that tells the user where that folder is.
Off'-hand, I do not remember which ones I added this to.
Here is my Add-Ins page.
Feel free to take a look.

One I added these to is the Table Cell Color Keyboard Shortcuts Add-In.
Here are the macros:

Code: Select all

Sub OpenStartupPath_TableShade()
'   Opens Windows Explorer window for Startup Folder
'   Charles Kyle Kenyon 2018-02-14
'
    Shell "explorer " & Application.StartupPath
  
End Sub

Code: Select all

Sub InstallAddIn_TableShade()
' Saves the template containing code in user's startup folder
' User must allow running of macro
' written by Charles Kenyon March 28, 2020
' https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-msoffice_custom/how-to-install-a-word-template-add-in-for-all/f41f816c-1c71-47ae-a570-519eff6bde07
'
    Dim strStartup As String
    strStartup = Application.StartupPath
    ThisDocument.SaveAs2 (strStartup & "\" & ThisDocument.Name)
    MsgBox prompt:="This will be active next time Word is started", _
        Title:=ThisDocument.Name & " Installed!"
End Sub
They can be triggered by the user via MacroButton fields in the Add-In.

snb
4StarLounger
Posts: 582
Joined: 14 Nov 2012, 16:06

Re: Macros blocked while testing Add-In + C# Documents.Open() question

Post by snb »

The simplest way to create an Addin and install it in Word I know:
Use a .docm file
To all macros you want the addin to contain, you add:

Code: Select all

Private Sub Document_Open()
    If ThisDocument.Type = 0 Then
       y = Len(ThisDocument.Name) - 4
       c00 = Application.Options.DefaultFilePath(2) & "\" & Left(ThisDocument.Name, y) & "dotm"
       ThisDocument.SaveAs2 c00
       AddIns.Add c00, True
    End If
End Sub
I can't consider this as 'complicated' or 'complex'.

User avatar
Charles Kenyon
5StarLounger
Posts: 620
Joined: 10 Jan 2016, 15:56
Location: Madison, Wisconsin

Re: Macros blocked while testing Add-In + C# Documents.Open() question

Post by Charles Kenyon »

snb wrote:
16 Jul 2023, 10:17
The simplest way to create an Addin and install it in Word I know:
Use a .docm file
To all macros you want the addin to contain, you add:

Code: Select all

Private Sub Document_Open()
    If ThisDocument.Type = 0 Then
       y = Len(ThisDocument.Name) - 4
       c00 = Application.Options.DefaultFilePath(2) & "\" & Left(ThisDocument.Name, y) & "dotm"
       ThisDocument.SaveAs2 c00
       AddIns.Add c00, True
    End If
End Sub
I can't consider this as 'complicated' or 'complex'.
It is not complex, but, like my macros, it requires that the user permit macros to run.

snb
4StarLounger
Posts: 582
Joined: 14 Nov 2012, 16:06

Re: Macros blocked while testing Add-In + C# Documents.Open() question

Post by snb »

NB. Loading another template simultaneously to the normaltemplate <> loading an AddIn.
There's no need a use a COM-addin, since VBA provides the same functionality.

Another method is adding a new reference to the normaltemplate:
In the usertemplate folder resides the template '__addin_install.dotm'

Code: Select all

Sub M_snb()
   With NormalTemplate
    .VBProject.References.AddFromFile Application.Options.DefaultFilePath(2) & "\__addin_install.dotm"
    .Save
   End With
End Sub

Comfrog
NewLounger
Posts: 6
Joined: 11 Jul 2023, 19:04

Re: Macros blocked while testing Add-In + C# Documents.Open() question

Post by Comfrog »

Well, thanks for the replies everyone.

I think that creating a .dotm file would be the best way to go about this issue. I think it would have been a very confusing journey of trying to make this work with an add-in. I also appreciated the methods for adding/installing macro-enabled templates, I will put them to good use :grin:

However, I reached another problem - So I'll just make a new post for this.