I am trying to populate word content controls using input from a spreadsheet. My code either doesn't work OR consistently work one time out of 2. I get the error 462.
Can someone help me to figure out what the problem is?
Thanks!
Private Sub Accept_Click()
Dim directory As String
Dim wrdApp As Word.Application
Dim doc As Word.Document
Dim fd As Office.FileDialog
Dim dt As String
Set wrdApp = CreateObject("Word.Application")
directory = Application.ActiveWorkbook.Path
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.InitialFileName = directory
.AllowMultiSelect = False
.Title = "Select doc letter"
.Filters.Add "All", "*.*"
If .Show = True Then
txtfilename = .SelectedItems(1)
End If
End With
wrdApp.Visible = True
On Error GoTo Handler
'i get error on the next line:
Set doc = wrdApp.Documents.Open(txtfilename, , False, , , , , , , , , True)
Documents(txtfilename).Activate
For Each cc In ActiveDocument.StoryRanges(wdPrimaryHeaderStory).ContentControls
If cc.Tag = "uptitle" Then cc.Range.Text = mill_box.Text
Next
For Each cc In ActiveDocument.StoryRanges(wdMainTextStory).ContentControls
If cc.Tag = "client" Then cc.Range.Text = TextBox1.Text & Chr(10) & TextBox2.Text _
& ", " & TextBox3 & Chr(10) & TextBox4 & " , " & TextBox5 & Chr(10) & TextBox6
If cc.Tag = "mill" Then cc.Range.Text = mill_box.Text
Next
ActiveDocument.Windows.Application.WindowState = wdWindowStateMaximize
Unload Me
ActiveDocument.Activate
Exit Sub
Handler:
Set wrdApp = Nothing
Set doc = Nothing
Unload Me
MsgBox "error"
End Sub
Interesting error!
Reading the info from this page (which was Google hit #2 for me on "error 462" - LMGTFY :) ) points to an answer discussed in a Microsoft knowledge base article:
You create a Word Application object through code, and assign it to a variable.
When you reference any of Word's Application members (like ActiveDocument) without the qualifying Application variable in front of it, VBA creates a hidden variable for it instead.
All seems fine, since VBA can call Word through both your own variable and the hidden one.
When you now set your own variables to Nothing, the hidden variable will still be there keeping Word alive.
When you come around a second time, the implicit hidden variable messes things up.
Your code also accesses ActiveDocument and Documents(txtfilename) instead of your own doc and wrdApp.
I do not know if this is a solution to your problem (no time to check it through), but it seems very applicable.
When it goes through without an error you are unloading Me and then exiting the sub. You don't set wrdApp and doc to Nothing like you do when there is an error. If you fix that logic so those get set to nothing on a successful run does it keep happening?
After a few days of trial and errors, here is the code that finally get things done. Thank you for everyone for taking your time to help me in this matter.
Private Sub Accept_Click()
Dim directory As String
Dim wrdApp As Word.Application
Dim doc As Word.Document
Dim fd As Office.FileDialog
On Error Resume Next
'this part is not necessary, but end users will know they can't have other word
'docs open when working with this file.
Set wrdApp = GetObject(, "Word.Application")
Set doc = wrdApp.Documents("Welcome letter.docx")
If Error <> 0 Then
Call Killword
End If
On Error GoTo Error_Handler
Set wrdApp = CreateObject("Word.Application")
directory = Application.ActiveWorkbook.Path
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.InitialFileName = directory
.AllowMultiSelect = False
.Title = "Select welcome letter"
.Filters.Add "All", "*.*"
If .Show = True Then
txtfilename = .SelectedItems(1)
End If
End With
'here is the thing: i had to instantiate the doc before making wrdapp visible.
Set doc = wrdApp.Documents.Open(txtfilename, , False, , , , , , , , , True)
wrdApp.Visible = True
doc.Activate
'from now on I have no choice than to refer to doc (not documents(1) or activedocuments! neither work)
For Each cc In doc.StoryRanges(wdPrimaryHeaderStory).ContentControls
If cc.Tag = "uptitle" Then cc.Range.Text = mill_box.Text
Next
For Each cc In doc.StoryRanges(wdMainTextStory).ContentControls
'here goes the code i need to execute on my word document. can be anything.
Next
doc.Windows.Application.WindowState = wdWindowStateMaximize
Unload Me
Exit Sub
Error_Handler:
Select Case Err.Number
Case 429, 91
Err = 0
Resume Next
Case Else
MsgBox ("An unexpected error has occured." & vbCrLf & vbCrLf & _
"Error number: " & Err.Number & vbCrLf & "Error description: " & Err.Description)
Resume Next
End Select
'Set wrdApp = Nothing
'Set doc = Nothing
Unload Me
End Sub
Related
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
I run VBA code in Access and update an existing Excel file.
I have to create xls files for each sales person and update the cells by grouping customer of monthly sales point by exporting data from an Access accdb file which is connected to Oracle database by ODBC driver.
We have about 50 sales persons and will have to create 2 files on each. If I can not fix the problem I will have 100 Excel processes on my PC. It might be frozen when run even if I successfully run the accdb with VBA.
Problems:
Can not close Excel process by Application.Quit which I tried to
open a xls file by Excel.Application.Workbooks object and it seems
be it's caught the xls file still even I used .Close
SaveChanges:=True
Can not process the VBA code again against same file cause of the
previous excel file operation process is left which I confirmed it
on task manager that I have to kill the process manually every time.
I googled on the internet and MSDN site. I could not find any good solution.
Option Compare Database
Const TARGET_SHEET = "SalesObjectiveSheet"
Const FILE_CREATION_WORK_FOLDER As String = "Work"
Const DESTINATION_ROOTPATH As String = "C:\Users\Administrator\Desktop"
Const TARGET_SHEET2 As String = "SalesObjectivesSheet"
Const HEADING_LINE_POSITION As Integer = 3
Public objApp As Excel.Application
Public objBooks As Excel.Workbooks
Public objBook As Excel.Workbook
Public objSheets As Excel.Worksheets
Public objSheet As Excel.Worksheet
Public Sub test200()
Dim str As Boolean
On Error GoTo Err_Handler
strSalesName = "SalesName"
strSalesOffice = "Tokyo"
strTargetFolder = DESTINATION_ROOTPATH & "\" & FILE_CREATION_WORK_FOLDER
strTargetFileName = "SalesObjectiveSheet_201708.xlsx"
strTargetFullPath = strTargetFolder & "\" & strTargetFileName
Set objApp = CreateObject("Excel.Application")
Set objBook = objApp.Workbooks.Open(strTargetFullPath)
Set objSheet = objBook.Worksheets(TARGET_SHEET2)
If EditObjectSheetHeader(objSheet, objApp, objBook, _
objBooks, strSalesName, strSalesOffice, strTargetFileName) = False Then
GoTo Err_Handler
End If
Exit_Handler:
objApp.Quit
Set objSheet = Nothing
Set objBooks = Nothing
Set objApp = Nothing
Exit Sub
Err_Handler:
' SysCmd acSysCmdRemoveMeter
Resume Exit_Handler
End Sub
Function EditObjectSheetHeader(objSheet As Object, objApp As Object, objBook As Object, _
objBooks As Object, strSalesName, strSalesOffice, strTargetFileName) As Boolean
Dim strProcedureName As String
Dim strMonth As String
On Error GoTo Err_Handler
objSheet.Select
objSheet.Activate
strProcedureName = "EditObjectSheetHeader"
EditObjectSheetHeader = False
With objSheet.PageSetup
.CenterHeader = "&14 " & "Month Sales Objectives"
.RightHeader = "" & Chr(10) & "Sales Office:" & strSalesOffice & " Name:" & strSalesName
.CenterFooter = "&P/&N"
.PrintTitleRows = "$1:$" & HEADING_LINE_POSITION
.LeftHeader = ""
End With
Exit_Handler:
Workbooks(strTargetFileName).Close SaveChanges:=True
' Frozen after I run the VBA code once cause of previous & _
process use same file is existed it seems be.
' ActiveWorkbook.Close saveChanges:=True
' Frozen after I run the VBA code once cause of & _
previous process use same file is existed & _
(Object and With is not defined error)
' objBook.Close SaveChanges:=True
' Frozen after I run the VBA code once cause of & _
previous process use same file is existed & _
it seems be.
' ActiveWorkbook.Close SaveChanges:=True
' Error unknown.
' ThisWorkbook.Save
'Error 1004 unknown.
EditObjectSheetHeader = True
Exit Function
Err_Handler:
Select Case Err.Number
Case 9
Debug.Print strProcedureName, Err.Number, Err.Description
MsgBox Err.Description & " " & Err.Number, vbOKOnly, strProcedureName
Case 70
Debug.Print strProcedureName, Err.Number, Err.Description
MsgBox Err.Description & " " & Err.Number, vbOKOnly, strProcedureName
Resume
Case Else
Debug.Print strProcedureName, Err.Number, Err.Description
MsgBox Err.Description & " " & Err.Number, vbExclamation, strProcedureName
End Select
End Function
Below line helped, but any other opened xls also will be closed:
Shell "taskkill /F /IM EXCEL.EXE /T"
Try placing objApp.Quit after releasing references.
Set objSheet = Nothing
Set objBooks = Nothing
Set objApp = Nothing
If Not objApp is Nothing Then objApp.Quit
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
I'd like to loop through a folder of PDF files and insert file into the appropriate text box of a word document.
I couldn't find much online about it, but I tried to model my code on looping through a folder of excel files... I haven't attempted to get it to insert the PDFs but am trying to tackle this problem first. BTW I have Adobe Reader and not Adobe Professional, if that helps.
I debugged the code and the error is on Set fromPDF = AcroExch.PDDoc.Open(sPath & sFile)...
Any help would be appreciated.
Sub UseTextBox()
Dim reportDoc As Object
Dim str As String
Dim tag As String
Dim pdfName As String
Set reportDoc = ActiveDocument
MsgBox reportDoc
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
'match PDF to figure and insert
Set SelectFolder = Application.FileDialog(msoFileDialogFolderPicker)
With SelectFolder
.Title = "Select Directory"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo ResetSettings
sPath = .SelectedItems(1) & "\"
End With
sFile = Dir(sPath & "*pdf")
Do While sFile <> ""
Set fromPDF = AcroExch.PDDoc.Open(sPath & sFile)
pdfName = sFile
For Each objShape In reportDoc.Shapes
If objShape.Type = msoTextBox Then
str = objShape.TextFrame.TextRange.Text
If InStr(str, "(") > 0 Then
tag = BetweenParentheses(objShape.TextFrame.TextRange)
MsgBox tag
End If
End If
Next objShape
sFile = Dir
Loop
ResetSettings:
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub
Where are you creating the AcroExch object? I think that might be your issue.
You may need something like:
Set MyObject = CreateObject("AcroExch.PDDoc")
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