Excel VBA to modify word documents with bookmarks - excel

I have a problem with my code below. I created an userform in order to generate Word documents automatically which I prepared (I created a bunch of bookmarks).
It works really well on my computer but not on another computer and I really don't understand why. Both computers have the same Office version (1902) and I have activated the Microsoft Word 16.0 Object Library reference.
What I mean by "it's not working" it is that the Word document will open but no action will be Performed... And also I have not a single error message.
Private Sub BCO_Click()
Dim objWord As New Word.Application, wordDoc As Word.Document
'FCO is the userform and the subobjects are combobox entries.
If FCO.SOCIETENAME <> "" And FCO.NUMCO <> "" And FCO.ComboBox1 <> "" Then
Dim pathcovierge As String
Dim pathconew As String
'Path of the files needed there, copy from an existing (pathcovierge) to a new one (pathconex)
pathcovierge = path & "\Documents_Vierges\" & "CO.docx"
pathconew = path & "\CO\CO_" & UCase(FCO.SOCIETENAME.Value) & "_" & UCase(FCO.NUMCO.Value) & ".docx"
If Dir(path & "\CO\", vbDirectory) = "" Then MkDir path & "\CO\"
'If file already open, msgbox
On Error Resume Next
FileCopy pathcovierge, pathconew
If Err > 0 Then
MsgBox "Veuillez fermer CO.docx afin de générer un CO."
End If
'opening of the new word document
objWord.Visible = True
objWord.Documents.Open pathconew
Dim DocDest As Word.Document
Set DocDest = GetObject(pathconew)
'THIS IS NOT WORKING.
DocDest.Bookmarks("WNUMCO").Range.Text = FCO.NUMCO.Value
DocDest.Bookmarks("WDATECO").Range.Text = FCO.DATECO.Value
DocDest.Bookmarks("WNOMCLIENT").Range.Text = FCO.SOCIETENAME.Value
'Saving (working)
DocDest.SaveAs pathconew
AppActivate ("CO_" & UCase(FCO.SOCIETENAME.Value) & "_" & UCase(FCO.NUMCO.Value) & ".docx")
On Error GoTo 0
Else
MsgBox "Veuillez rentrer tous les champs obligatoires (*)"
End If
End Sub

I took a look in your code and made some changes (also see my comments in the code):
I enhanced the readability by early exiting the procedure instead of using 'arrow code'.
Now the opened Word document will be set to the variable immediately.
Your error handling suppressed all errors. I changed it, but you should add proper error handling though. Think about splitting your procedure in several separate procedures.
This should lead you to your result:
Private Sub BCO_Click()
If FCO.SOCIETENAME = "" Or FCO.NUMCO = "" Or FCO.ComboBox1 = "" Then
MsgBox "Veuillez rentrer tous les champs obligatoires (*)"
Exit Sub
End If
Dim pathcovierge As String
pathcovierge = path & "\Documents_Vierges\" & "CO.docx"
Dim pathconew As String
pathconew = path & "\CO\CO_" & UCase(FCO.SOCIETENAME.Value) & "_" & UCase(FCO.NUMCO.Value) & ".docx"
If Dir(path & "\CO\", vbDirectory) = "" Then MkDir path & "\CO\"
'This seems to be the reason why you get no error:
On Error Resume Next
FileCopy pathcovierge, pathconew
If Err > 0 Then
MsgBox "Veuillez fermer CO.docx afin de générer un CO."
End If
'This will let you see a possible error, but you should think about implement a proper error handling though:
On Error Goto 0
Dim objWord As Word.Application
Set objWord = New Word.Application
objWord.Visible = True
Dim docDest As Word.Document
'If the problem was to get the handle to the opened document, this should work better:
Set docDest = objWord.Documents.Open(pathconew)
docDest.Bookmarks("WNUMCO").Range.Text = FCO.NUMCO.Value
docDest.Bookmarks("WDATECO").Range.Text = FCO.DATECO.Value
docDest.Bookmarks("WNOMCLIENT").Range.Text = FCO.SOCIETENAME.Value
docDest.SaveAs pathconew
AppActivate ("CO_" & UCase(FCO.SOCIETENAME.Value) & "_" & UCase(FCO.NUMCO.Value) & ".docx")
End Sub

Related

Excel to Word Macro resulting in Run-time error 462

I've written a VBA macro which resides in an Excel workbook. When run, it will open an existing Word document (which is stored in the same directory as the Excel workbook), copy some content from cells in the Excel workbook into the Word document, save the Word doc under a new name (in the same directory) and kill the original Word doc. This process works as expected on first run. But on a second run, I get a Run-time error 462. I'm sure it's due to my ignorance around creating and using application instances within VBA code (I've just begun learning). I'm using Microsoft 365 Apps for Enterprise.
Sub ExcelToWord()
Dim wordApp As Word.Application
Dim wDoc As Word.Document
Dim strFile As String
'Open Word file
strFile = ("G:\HOME\Word File.docx")
Set wordApp = CreateObject("word.Application")
Set wDoc = wordApp.Documents.Open("G:\HOME\Word File.docx")
wordApp.Visible = True
'Copy data from Excel to Word
wDoc.ContentControls(1).Range.Text = Sheets("Model").Cells(4, 2)
wDoc.ContentControls(2).Range.Text = Format(Date, "mm/dd/yyyy")
wDoc.ContentControls(3).Range.Text = Sheets("Model").Range("X4")
Word.Application.Activate
'Save Word Document with new name
ActiveDocument.SaveAs Filename:=ActiveDocument.Path & "\" & Format(Sheets("Model").Range("B14"), "YYYY") & " " & ThisWorkbook.Sheets("Model").Range("B4") & " " & Format(Date, "YYYY-mm-dd") & ".docx"
'Delete original Word document
Kill strFile
End Sub
I've researched this for hours and tried multiple solutions, including commenting out all of the Copy Data block to try and zero in on the error. But no luck. I hope I've posted this request properly. Thank you in advance for any help.
Is this what you are trying? I have commented the code but if you face any issues, simply ask. What you have is Early Binding. I have used Late Binding so that you do not need to add any references to the MS Word application.
Option Explicit
Private Const wdFormatXMLDocument As Integer = 12
Sub ExcelToWord()
Dim oWordApp As Object, oWordDoc As Object
Dim FlName As String
Dim FilePath As String
Dim NewFileName As String
'~~> This is the original word file. Change as applicable
FlName = "G:\HOME\Word File.docx"
'~~> Check if word file exists
If Dir(FlName) = "" Then
MsgBox "Word File Not Found"
Exit Sub
End If
'~~> Establish an Word application object if open
On Error Resume Next
Set oWordApp = GetObject(, "Word.Application")
'~~> If not open then create a new word application instance
If Err.Number <> 0 Then
Set oWordApp = CreateObject("Word.Application")
End If
Err.Clear
On Error GoTo 0
oWordApp.Visible = True
Set oWordDoc = oWordApp.Documents.Open(FlName)
With oWordDoc
'~~> File path
FilePath = .Path & "\"
'~~> New File name
NewFileName = FilePath & _
Format(ThisWorkbook.Sheets("Model").Range("B14").Value, "YYYY") & _
" " & _
ThisWorkbook.Sheets("Model").Range("B4").Value & _
" " & _
Format(Date, "YYYY-mm-dd") & ".docx"
'~~> Copy data from Excel to Word
.ContentControls(1).Range.Text = Sheets("Model").Cells(4, 2).Value2
.ContentControls(2).Range.Text = Format(Date, "mm/dd/yyyy")
.ContentControls(3).Range.Text = Sheets("Model").Range("X4").Value2
'~~> Save the word document
.SaveAs Filename:=NewFileName, FileFormat:=wdFormatXMLDocument
DoEvents
End With
'~~> Delete original Word document
Kill FlName
End Sub

Function Dir() not working as excepted : Error Code 5 : Invalid argument or procedure call

I'm trying to set a macro which will moove file from a certain folder to another one, If this file already exists then it will display a message box if a file from an other folder already exist in a folder. Here is the problem..
I think the first error is here :
StrFile = Dir
Here is the error it display me the error code : 5 Invalid argument or procedure call
And the excepted output of this line code is to go to next file in order to browse all my .Pdf file one per one
Sub MooveFile()
Dim filepath As String
Dim currfile As String
Dim NomFichier As String
Dim Direction As String
Dim StrFile As String
Dim FSO As Object
Dim SourceFileName As String, DestinFileName As String
StrFile = Dir(ActiveWorkbook.Path & "\" & "*.PDF")
Do While Len(StrFile) > 0
Direction = Split(StrFile, " ")(0)
Set FSO = CreateObject("Scripting.Filesystemobject")
SourceFileName = ActiveWorkbook.Path & "\" & StrFile
Set FoundRange = Sheets("Path").Cells.Find(what:=Direction, LookIn:=xlFormulas, lookat:=xlWhole)
If FoundRange Is Nothing Then 'Here is the test if the folder exist : WORKING
On Error Resume Next
MkDir ActiveWorkbook.Path & "\" & Direction
DestinFileName = ActiveWorkbook.Path & "\" & Direction & "\" & StrFile
FSO.MoveFile Source:=SourceFileName, Destination:=DestinFileName
Else 'If Folder exist : WORKING
DestinFileName = ActiveWorkbook.Path & "\" & Direction & "\" & StrFile
If Dir(SourceFileName) <> "" Then 'IF File exist then display the message box : WORKING
Select Case MsgBox("le fichier" & SourceFileName & "existe déjà voulez-vous le remplacer", vbAbortRetryIgnore)
Case vbAbort
' Cancel the operation.
MsgBox "Operation canceled"
Case vbRetry
' Continue the Do loop to try again.
FSO.DeleteFile DestinFileName, True
FSO.MoveFile Source:=SourceFileName, Destination:=DestinFileName
Case vbIgnore
' Take a default action.
GoTo nextline
End Select
Else
FSO.MoveFile Source:=SourceFileName, Destination:=DestinFileName
End If
'FSO.MoveFile Source:=SourceFileName, Destination:=DestinFileName
End If
nextline:
StrFile = Dir 'This line code is not working at : Error code 5 :Invalid argument or procedure call
Loop 'Fin Boucle
Application.ScreenUpdating = True
End Sub
Did I miss something here ? I already tried StrFile = Dir()
I'm not sure why you are using Dir when you are creating a FileSystemObject?
Although (in my experience) it is slower it is far more robust.
For a start, don't create it as an Object. Put a reference to Windows.Scripting then
Dim FSO As Scripting.FileSystemObject
set FSO= New Scripting.FileSystemObject
Apart from anything else, it will give you the Intellisense which makes life easier.
You can then check for a file/folder with
If FSO.FileExists(myFile) Then
If FSO.FolderExists(myFolder) Then
And start to use collections such as
Dim fi As Scripting.File
For Each fi In FSO.GetFolder(myFolder).Files
Next
Microsoft Reference

Using a MAC, print a Word document using a macro in Excel

I am using a MAC and I'm trying to create a macro that will print a Word document from my Excel worksheet. The user does not need to see the word document, they just need to print it.
After looking through some of the previous questions answered in this forum I managed to write some code that worked on my PC at home.
However, I changed the file path and filename and copied the code to my MAC that I am using at work and the code no longer seems to work. I wonder if the code has to be different when using a MAC?
I am using Microsoft Excel for Mac 2011, version 14.6.8.
ans = MsgBox(Prompt:="Document 1", Buttons:=vbYesNo, Title:="Print")
If ans = vbYes Then
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
'Enter filename and path here
Set objDoc = objWord.Documents.Open("/Volumes/.../Document 1.docx")
objWord.Visible = False
objDoc.PrintOut
objWord.Quit
End If
Sometimes the code gets stuck at CreateObject("Word.Application") and sometimes the code get stuck where I have written the file path and filename.
I'm not entirely sure that I have written the file path correctly..?
Any help would be much appreciated.
Is your file on a network?
Use that code in Word VBE to get the path of your file in the immediate window :
Sub get_path()
Debug.Print ActiveDocument.Path
End Sub
Try this function to test if the file exists (not sure how to make this work on Mac...) :
Public Function File_Exist(sFilePath As String) As Boolean
Dim sProv As String
On Error GoTo ErrorHandler
sProv = Dir(sFilePath, vbDirectory)
File_Exist = (sProv <> "")
On Error GoTo 0
Exit Function
ErrorHandler:
MsgBox Prompt:="Error on test file= " & sFilePath & vbCrLf & Err.Number & vbCrLf & Err.Description
End Function
And your code with some improvements :
ans = MsgBox(Prompt:="Document 1", Buttons:=vbYesNo, Title:="Print")
If ans = vbYes Then
Dim objWord As Object
Dim objDoc As Object
Dim sFilePath As String
''If the file is a network, you should start the path with //
sFilePath = "New_path_from_Word_immediate_window"
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set objWord = CreateObject("Word.Application")
End If
On Error GoTo 0
objWord.Visible = False
'Enter filename and path here
'If File_Exist(sFilePath) Then
Set objDoc = objWord.Documents.Open(sFilePath)
objDoc.PrintOut
objDoc.Close
'Else
'MsgBox "File doesn't exist!" & vbCrLf & sFilePath, vbCritical + vbOKOnly
'End If
objWord.Quit
End If

Excel vba can't release winword.exe

I'm opening multiples Word doc to remove the protection in them.
So basically what my code is doing is that if user choose to enter a password then:
valeur = 6
and pwd is set to a specific value.
My problem is even if I do: set WdApp = nothing, it still won't release the winword.exe process.
Do While Len(F) > 0
If F = nom_fichier Then 'file name
nom_original = chemin & "\" & F 'path
nom_copie = repertoire_cible & "\" & nom_fichier 'copy of a file
nom_modifie = repertoire_cible & "\" & nom_en_preparation 'rename of file
If Dir(nom_original, vbDirectory) = vbNullString Then
GoTo fichier_non_trouve
End If
If Not Dir(nom_modifie, vbDirectory) = vbNullString Then GoTo fichier_deja_existant:
End If
FileCopy nom_original, nom_copie 'file copy
Name nom_copie As nom_modifie ' file rename
If valeur = 6 Then 'protection removal
Set WdApp = CreateObject("Word.Application")
Set WdApp = Documents.Open(nom_modifie)
If Not WdApp.ProtectionType = -1 Then WdApp.Unprotect pwd
WdApp.Close True
Else
WdApp.Close True
End If
Set WdApp = Nothing
End If
GoTo fichier_copier:
End If 'on copie le fichier dans le dossier en préparation
F = Dir()
Loop
So at this point since I called Set WdApp = nothing I don't see why it's not releasing the winword.exe.
Any kind help will be really appreciate
Keep a reference to the application and the doc independently and .Quit the application:
Set WdApp = CreateObject("Word.Application")
Set WdDoc = Documents.Open(nom_modifie)
... use wdDoc
WdDoc.close True
WdApp.Quit
But why not create WdApp outside the loop and open docs as needed, quitting the application when your done.

Excel VBA Password Protection check [duplicate]

This question already has an answer here:
Ignore Excel Files That Are Password Protected [duplicate]
(1 answer)
Closed 8 years ago.
I have a project in which I have to go over 1,000+ excel files in a folder, and see which ones are password protected and which ones aren't. In order to save time, I wrote a macro to do this, which is as follows:
Sub CheckWbook()
Dim Value As String, a As Single, myfolder as string
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
myfolder = .SelectedItems(1) & "\"
End With
Range("C4") = myfolder
Range("B7:C" & Rows.Count) = ""
a = 0
Value = Dir(myfolder)
Do Until Value = ""
If Value = "." Or Value = ".." Then
Else
If Right(Value, 3) = "xls" Or Right(Value, 4) = "xlsx" Or Right(Value, 4) = "xlsm" Then
On Error Resume Next
Workbooks.Open Filename:=myfolder & Value, Password:="zzzzzzzzzzzz"
If Err.Number > 0 Then
Range("C7").Offset(a, 0).Value = "Yes"
End If
Workbooks(Value).Close False
On Error GoTo 0
Range("B7").Offset(a, 0).Value = Value
a = a + 1
End If
End If
Value = Dir
Loop
End Sub
The problem I'm having is that the popup for the password is still present: it does not fill in the password. Any help would be highly appreciated. -A
Edit
Changed the code a bit, and got past the error message, but now I'm getting stuck at the password popup, that stops the macro from completely working, despite the On Error Resume Next feature.
Then, I came across this code that I thought could help:
Option Explicit
Public Sub ProcessBatch()
Dim strFileName As String
Dim strFilePath As String
Dim oDoc As Document
' Set Directory for Batch Process
strFilePath = "C:\Test\"
' Get Name of First .doc File from Directory
strFileName = Dir$(strFilePath & "*.doc")
While Len(strFileName) <> 0
' Set Error Handler
On Error Resume Next
' Attempt to Open the Document
Set oDoc = Documents.Open( _
FileName:=strFilePath & strFileName, _
PasswordDocument:="?#nonsense#$")
Select Case Err.Number
Case 0
' Document was Successfully Opened
Debug.Print strFileName & " was processed."
Case 5408
' Document is Password-protected and was NOT Opened
Debug.Print strFileName & " is password-protected " & _
"and was NOT processed."
' Clear Error Object and Disable Error Handler
Err.Clear
On Error GoTo 0
' Get Next Document
GoTo GetNextDoc
Case Else
' Another Error Occurred
MsgBox Err.Number & ":" & Err.Description
End Select
' Disable Error Handler
On Error GoTo 0
'-------------------------------------
'-------------------------------------
'---Perform Action on Document Here---
'-------------------------------------
'-------------------------------------
' Close Document
oDoc.Close
' Clear Object Variable
Set oDoc = Nothing
GetNextDoc:
' Get Next Document from Specified Directory
strFileName = Dir$()
Wend
End Sub
but this fails to recognize the oDoc as a Document. Any ideas on how to get it working?
to open the excel file? or sheet
if it is a sheet should be
ActiveSheet.Unprotect Password: = "yourpassword"
if it is an excel
ActiveWorkbook.Unprotect("youtpassword")
I hope it serves you a hug I learned a lot here I hope you will also hopefully serve my help

Resources