Word macro working on every document - vba

I have written a macro in Word and it works every time I open ANY of Word documents. I don't know what is the reason for such an action and I'd like to ask you why?
Private Sub Document_Open()
Dim fso As Object
Dim f As Object
Dim plik As Object
Dim sciezka As String
ActiveDocument.Content.Select
Selection.Delete
ActiveDocument.Select
sciezka = Application.ActiveDocument.Path & "\"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(Application.ActiveDocument.Path)
For Each plik In f.Files
If Not Left(Right(plik.Name, 8), 4) = "rozp" And Right(plik.Name, 4) = ".pdf" Then
Selection.TypeText plik.Name
Selection.TypeParagraph
End If
Next plik
End Sub

You probably stored it in normal.dotm document This code will apply to all documents. You should move it and store it in module that is in the document your are dealing with.
Edit 1: You created a .docm document but are you sure you stored your code in the docm document and not in the normal.dotm document?
Edit 2: I created a word test.docm document and put your code in a new module (under project(Test) -> Modules -> Module 1). Then I started the code and it create 1 paragraph per files in the same folder (giving they respect the check in your IF condition). Then, I transfered that code in Project(Test) -> Microsoft Word Objects -> ThisDocument; so it works at opening. It does exactly the same as intended at the opening.
Finally, I tested opening other word documents (docx and docm) in the same folder and the code did not run.
I cannot reproduce your problem running the exact same code. This reinforce the idea that you wrote your code under Normal -> Microsoft Word Object -> ThisDocument while in the VBA frame.
Have a good day,
Jonathan.

Related

Printing pdf through automating word with VB net without showing dialog

I've finally encountered a problem, where I didn't already find the answer here or anywhere else on the web:
My program grabs some measurement values from an instrument (I cannot directly control it so I have to wait until the measurement was done by the user and parse the report), calculates some derived values and shall put these values back into the pdf report, which was automatically generated by the instrument control software.
It all works until I come to the line where the printout is started. It always opens the word print dialog instead of silently overwriting my file. I actually don't understand what I am doing wrong when calling PrintOut.
Here is the example code:
Imports Microsoft.Office.Interop
Module Example
Private Sub PrintReport()
Dim intAnswer As Integer
Dim strReportFileName As String = ""
Dim appWord As New Word.Application
Dim wdDoc As Word.Document
dim strPPF as string = "0.5" 'For testing, normally a parameter
dim strFolder as string = "C:\UVVis-Data" 'For testing, normally a parameter
'Find and open the PDF file of the report:
strReportFileName = (From fi As IO.FileInfo In (New IO.DirectoryInfo(strFolder.GetFiles("*.pdf")) Order By fi.LastWriteTime Descending Select fi)(0).FullName 'It will be always the newest file in that folder
appWord.Visible = False 'hide word from the user
wdDoc = appWord.Documents.Open(strReportFileName) 'open the PDF report
'Replace the placeholders which were defined in the report template earlier:
With appWord.Selection.Find
.Text = "#PPF#"
.Replacement.ClearFormatting()
.Replacement.Text = strPPF
.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
End With
'Print out the modified report:
'wdDoc.PrintOut(False, False,, strReportFileName,,,,,,, True) 'this was my first approach
wdDoc.PrintOut(Background:=False, Append:=False, OutputFileName:=strReportFileName, PrintToFile:=True) 'this also doesn't work as intended
'Close the file and restore word to it's normal state:
wdDoc.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges)
appWord.Visible = True
appWord.Quit()
End Sub
end Module
Use the Document.ExportAsFixedFormat method which saves a document as PDF or XPS format.
Public Sub ExportAsFixedFormat_Example()
wdDoc.ExportAsFixedFormat pbFixedFormatTypePDF, "pathandfilename.pdf"
End Sub
Thank you for the input.
I found a second problem with my code: I cannot overwrite the original document once it is open in word.
I solved this by first moving the pdf to a temporary folder, opening that temporary file in word and deleting it after word is closed.

Apply code to active document not document opened with Documents.Add

I got a VBA project from colleague who is retired.
I have to change a function:
Documents.Add Template:= _
"c:\word\Link.dot", _
NewTemplate:=False, DocumentType:=0
Here a new document (another Word file) is created with a template.
This template also relates data from another project "Common".
Basically, Documents.Add Template:= _"c:\word\Link.dot"
in Link.dot the Document_Open() is executed and the Common project is initialized.
Private Sub Document_Open()
Common.Initialize
End Sub
I don't want a second document opened by Documents.add, it should use the already active document.
I tried these two variants:
#1
Dim oDoc As Document
Set oDoc = ActiveDocument
oDoc.AttachedTemplate = "c:\word\Link.dot"
#2
ActiveDocument.AttachedTemplate = "c:\word\Link.dot"
Nothing happens to both of them, even no Runtime Error. I think it's because Document_Open() wasn't executed.
Document_Open() responds to the Open event. As you are not opening a document when attaching the template it will not execute.
You can execute the code directly though.
ActiveDocument.AttachedTemplate = "c:\word\Link.dot"
Common.Initialize

MS Word does not unlink fields for one document but does for another

I have some VBA code (In Excel) that will open a Word document, break the links, and save that Word document elsewhere.
All automated and transport to the user, all they will see is a file appear in a folder.
My problem is it works for the below:
Private Sub Button1_Click()
Dim objWord As Object
Dim docWord As Object
Const wdDoNotSaveChanges As Long = 0
Set objWord = CreateObject("Word.Application")
Set docWord = objWord.Documents.Open(ThisWorkbook.Path & "\A folder\Myfile.doc")
objWord.ActiveDocument.Fields.Unlink
objWord.ActiveDocument.SaveAs ThisWorkbook.Path & "\" + Cells(1, 7) + "myfile.doc"
objWord.ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
objWord.Quit
End Sub
but not for the below which is supposed to perform the same function on a different Word document:
Private Sub Button2_Click()
Dim objWord As Object
Dim docWord As Object
Const wdDoNotSaveChanges As Long = 0
Set objWord = CreateObject("Word.Application")
Set docWord = objWord.Documents.Open(ThisWorkbook.Path & "\A Folder\Myfile2.doc")
objWord.ActiveDocument.Fields.Unlink
objWord.ActiveDocument.SaveAs ThisWorkbook.Path & "\" + Cells(1, 7) + "MyFile2.doc"
objWord.ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
objWord.Quit
End Sub
When I open the first document generated (outcome of the first code), it doesn't ask me to update the links and the links are broken, as intended.
When I open the second document generated (Outcome of the second code), it asks me to update the links.
EDIT:
Both sections of code above have been merged and put into a single sub that has variables forwarded to it - Still same outcome of one document updating and unlinking as intended, the other document asking the user on opening if they want to update links.
So now most likely a problem with the Word documents.
Both Word documents are linked to Excel via Paste Special > Paste Link.
Both only linked to the one Excel document.
The only difference I can see is one document has quite a few more links than the other, but surely quantity of links shouldn't matter?
Upon further investigation, the problem is confined to the header of the document. My code will unlink all fields in the body of the document, but will not do this for the header. As a result, the header remains linked and it asks the user if they would like to update.
I eventually found my solution here:
VBA Excel - Unlink headers & footers in Word

VBA Excel - Unable to open existing Word Document file

I have a simple macro that opens a Word Document using Excel. I made sure the Word Object Library is properly referenced but when running this macro it freezes after Documents.Open is called (based on me seeing where it fails in the debugger). I don't know if it is a OLE Automation Error but the macro freezes and I have to force close Excel.
Public Const Dir = "C:/Temp/"
Public Const File = "temp.docx"
Public Sub OpenFile()
Dim f As String: f = Dir & File
Dim oWord As Object, oDoc As Object
Set oWord = CreateObject("Word.Application")
Set oDoc = oWord.Documents.Open(f)
oDoc.Visible = True
End Sub
I get this message as well: (even though there is no other application open)
Is there an alternative to opening a file with Excel and how I rewrite my program?
As requested - this is a common problem
You should change your Dir variable - that's a reserved name - and you're probably getting a Word error you can't see when you try to open that "file".
You should also change your File variable name too - that can be a reserved word too depending on references you've set
Added Comment:
With regard to it freezing - you can remove the oDoc.Visible = True statement and replace it with oWord.Visible = True BEFORE the problem statement Set oDoc = oWord.Documents.Open(f). That would popup the error indicating you had a problem with your filename

Save Excel Sheet text only to text file VBA

I am trying to copy the values of one column in a sheet to a text file. The code I currently have causes runtime error 434.
Sheets("Output to fcf.1").Columns("A").SaveToText "P:\4_Calcs\02. Flag Mapping\test_.txt"
If I try and save the whole sheet
Sheets("Output to fcf.2").SaveToText "P:\Clear Project Drive\CLE10276 AWS SMP Model Assessmnts\4_Calcs\02. Flag Mapping\test2_.txt"
I get the entire sheet converted into text rather than just the text in the sheet. Is there a simple way to do this?
Thanks in advance!
Not sure which Excel version you have but I don't see a method for SaveToText.
But this procedure should work, or at least get you started...
Sub SaveColumn(sheetName As String, columnName As String, fileName As String)
Dim cell
Dim fso
Dim file
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.CreateTextFile(fileName, True)
For Each cell In Sheets(sheetName).Columns(columnName).Cells
If cell.Value <> "" Then
file.WriteLine cell.Value
End If
Next
file.Close
Set file = Nothing
Set fso = Nothing
End Sub
To call it...
SaveColumn "Output to fcf.1", "A", "P:\4_Calcs\02. Flag Mapping\test_.txt"
This is designed to be used as a macro.
Step by step guide:
1) From excel, hit Alt+F11 on your keyboard.
2) From the menu bar, click Insert, then Module
3) Copy and paste the code provided below into the new module that opens.
NOTE: DocPath = "C:\docs\data.txt" should be wherever you want the output file saved, including the file's actual name. Remember, the folder you want the output file to be located in should ALREADY exist. This does not create the folder if it can't be found.
4) From the menu bar, click Tools, then References. Make sure both "Microsoft Office 14.0 Object Library" as well as "Microsoft Word 14.0 Object Library" are checked, and hit okay (See screenshot for details)
5) Save the document as an .xlsm file (This file type supports Macros)
6) Close the VBA editor. Back in Excel, on the ribbon click View and then Macros. Your new macro should be in the list as ExportToTXT
7) Select it and hit run.
Sub ExportToTXT()
Dim DocPath As String
Dim MsgBoxCompleted
Columns("A").Select
Dim AppWord As Word.Application
Set AppWord = CreateObject("Word.Application")
AppWord.Visible = False
Selection.Copy
DocPath = "C:\docs\data.txt"
'Create and save txt file
AppWord.Documents.Add
AppWord.Selection.Paste
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath, FileFormat:=wdFormatText
Application.CutCopyMode = False
AppWord.Quit (wdDoNotSaveChanges)
Set AppWord = Nothing
MsgBoxCompleted = MsgBox("Process complete.", vbOKOnly, "Process complete")
End Sub
Good luck, and if you have any questions, don't hesitate to ask.
NOTE: These directions might seem overly simplified for your skill level, but I wrote the answer like this to potentially help others in the future.
EDIT
Change
DocPath = "C:\docs\data.txt"
to
DocPath = "C:\docs\data.fcf"
And change
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath, FileFormat:=wdFormatText
to
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath
The output file will be .fcf format. Whether or not it will open properly is something I'm not sure of. You'd have to test in the program you're using.