While coding and extending the functionality of my Sub there are sadly arising some errors - e.g. a runtime error - but it could be any error...
The main topic of my question is that for me it's impossible to open that specific Word document (Test.docx) by hand (clicking on it in the explorer).
I have found one solution but this one is annoying, because I have to restart my computer and this is time consuming... and I hope there exists a more elegant solution that you can share with me.
So many thanks in advance!
Now my code with an provoked error...
Sub GetInfoOutOfWordDocument()
'Init
Dim appWord As Word.Application
Dim document As Word.Document
Dim strFolder As String
Dim strFile As String
Dim MyArray() As Variant ' for arising the error
' Select the word document
strFolder = "C:\Users\"
strFile = Dir(strFolder & "Test.docx", vbNormal)
' Open the word document
Set appWord = CreateObject("Word.Application")
Set document = appWord.Documents.Open( _
FileName:=strFolder & "\" & strFile, AddToRecentFiles:=False, ReadOnly:=False, Visible:=False)
' Getting the needed information out of your Word document...
' Now the error occurs - e.g. runtime error
MyArray(1)=5
' Problem: The above opened Word document isn't closed properly and therefore
I'm not able to open the specific Word document by hand
dokument.Close wdDoNotSaveChanges
appWord.Quit
Set document = Nothing
Set appWord = Nothing
End Sub
Related
I am trying to set the path to my Workbook file, which I want to be opened from the same directory, where my current workbook is based.
I saw some solution here:
Open File Without Calling Filepath
and my code currently looks like this:
Sub RamsOpen3()
Dim appWD As Word.Application
Set appWD = New Word.Application
Dim docWD As Word.Document
Set docWD = appWD.Documents.Open ActiveWorkbook.Path & "RAMS.docx.docm")
appWD.Visible = True
'
' Data is selected and copied into "Design"
'
'Copy all data from Design
Sheets("Frontsheet").Select
Range("D18").Copy
' Tell Word to create a new document
appWD.Selection.Paste
' Save the new document with a sequential file name
Sheets("Sheet1").Select
appWD.ActiveDocument.SaveAs filename:=ThisWorkbook.path & "/" & "TEST" & Range("C8").Text
' Close this new word document
appWD.ActiveDocument.Close
' Close the Word application
appWD.Quit
End Sub
The line of code is in red, and the debugger says: Expected end of statement.
It excludes also the option with Dim filename as string, proposed in the linked query above.
Does anyone know how to coup with it?
What I am trying to do:
Export a range of cells from an Excel worksheet as an image in an existing Word document, and then saving this Word document as both a Word document and a PDF file. The name both the Word file and the PDF file should get, is in a cell in the Excel worksheet.
The problem:
Almost everything works, except for the .pdf-file. It is generated, but when trying to open it I get an error, saying the file is unreadable.
Can someone help with this? The code I use is below - I assembled it from different examples on this and other forums (I really am a VBA beginner)...
Thank you so much!
The Code:
Sub SaveAsWord()
Dim WordApp As Object
Set WordApp = CreateObject("Word.Application")
Dim WordDoc As Object
Set WordDoc = WordApp.Documents.Open("C:\Users\Jurgen\Documents\remake.docx")
Range("C4:E19").Select
Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
WordApp.Visible = True
WordApp.ActiveDocument.Bookmarks("here").Select
Set objSelection = WordApp.Selection
objSelection.Paste
Dim myfilename As String
myfilename = Sheets("Blad1").Range("G15")
WordApp.ActiveDocument.SaveAs2 Filename:="C:\Users\Jurgen\Documents\" & myfilename & ".pdf", _
FileFormat:=wdFormatPDF
WordApp.ActiveDocument.SaveAs2 Filename:="C:\Users\Jurgen\Documents\" & myfilename & ".docx", _
FileFormat:=wdFormatXMLDocument
End Sub
As you do not use Early Binding and it also seems that you do not use Option Explicit the root cause will be that wdFormatPDF is 0 and it should be 17.
Either you use Option Explicit and Early Binding or you just replace the constants with the values like that
WordApp.ActiveDocument.SaveAs2 Filename:="C:\Users\Jurgen\Documents\" & myfilename & ".pdf", _
FileFormat:=17
and
WordApp.ActiveDocument.SaveAs2 Filename:="C:\Users\Jurgen\Documents\" & myfilename & ".docx", _
FileFormat:=12
Reading material
Option Explict
Early vs Late Binding
Late Binding
Microsoft on Using early binding and late binding in Automation
I am trying to write some macros in both Excel and Outlook that in the end will automatically unzip and open a CSV, process the data, and sends it where it needs to go when a new email arrives in a specific folder. I have everything worked out on the Excel side but I am having difficulties with Outlook. The below code unzips the file. How would i go about opening the unzipped file and triggering an Excel macro (which is always open in another workbook)?
Another issue I am running into: this code only seems to work when i actually open the target email in it's own window.
Public Sub OpenZippedSheet()
Dim objMail As Outlook.MailItem
Dim objAttachments As Outlook.Attachments
Dim objAttachment As Outlook.Attachment
Dim objShell As Object
Dim objFileSystem As Object
Dim strTempFolder As String
Dim strFilePath As String
Dim strFileName As String
Set objMail = Outlook.Application.ActiveInspector.CurrentItem
Set objAttachments = objMail.Attachments
'Save & Unzip the zip file in local drive
Set objShell = CreateObject("Shell.Application")
Set objFileSystem = CreateObject("Scripting.FileSystemObject")
strTempFolder = objFileSystem.GetSpecialFolder(2).Path & "\Temp" & Format(Now, "yyyy-mm-dd-hh-mm-ss")
MkDir (strTempFolder)
For Each objAttachment In objAttachments
If Right(objAttachment.FileName, 3) = "zip" Then
strFilePath = strTempFolder & "\" & objAttachment.FileName
objAttachment.SaveAsFile (strFilePath)
objShell.NameSpace((strTempFolder)).CopyHere objShell.NameSpace((strFilePath)).Items
End If
Next
End Sub
I'm assuming I would do some sort of object.open but I don't know what the syntax would be to get it to actually open in Excel. And then is there a way to trigger an Excel macro from Outlook?
Thanks so much in advance!
this code only seems to work when i actually open the target email in it's own window.
That is because you rely on the ActiveInspector window. If you want to handle items selected in the Explorer windows you need to check the Selection object (see the corresponding property).
To open an Excel file you can:
Use the Shell.ShellExecute method. This method is equivalent to launching one of the commands associated with a file's shortcut menu. Each command is represented by a verb string. The set of supported verbs varies from file to file. The most commonly supported verb is "open", which is also usually the default verb. Other verbs might be supported by only certain types of files.
Automate Excel from your VBA macro to do the required actions. See How to automate Microsoft Excel from Visual Basic for more information.
To run your VBA macro code from other applications you can use the Application.Run method. Read more about that in the How do I use Application.Run in Excel article.
Application.Run "'" & TestWkbk.Name & "'!MacroNameHere", "parm1", "parm2"
Something like this (untested so may need some fixes):
'Note - any paths passed to objShell should be
' passed as *Variants*, not Strings
Dim oXL As Object, wbCSV As Object, fileNameInZip As Variant
Set objShell = CreateObject("Shell.Application")
For Each objAttachment In objAttachments
If Right(objAttachment.Filename, 3) = "zip" Then
strFilePath = strTempFolder & "\" & objAttachment.Filename
objAttachment.SaveAsFile strFilePath
Set oNS = oApp.Namespace(strFilePath)
For Each fileNameInZip In oNS.items 'loop over the files in the zip
Debug.Print fileNameInZip
If LCase(fileNameInZip) Like "*.csv" Then 'csv file?
'extract the file
objShell.Namespace(strTempFolder).copyhere oNS.items.Item(CStr(fileNameInZip))
If oXL Is Nothing Then Set oXL = GetObject(, "Excel.Application") 'assumes excel is running
Set wbCSV = oXL.Workbooks.Open(strTempFolder & "\" & fileNameInZip)
oXL.Run "'YourMacroFile.xlsm'!YourMacroName" 'run the macro
'clean up stuff...
End If 'is a csv file
Next 'file in zip
End If 'attachment is a zip file
Next 'attachment
It seems to work for everyone else, but my exportasfixedformat always calls up a type 5 error.
I've tried: similar code to others, checking everything has been dimmed, using _, and more but I just can't get my head around it.
Dim wordApp As Object
Dim wordDoc As Object
Dim newName As String
Dim FilE As String
Dim filePath As String
Public Sub MainCode()
filePath = "X:\Invoices\10.4.1 RFPOs\"
FilE = "X:\Invoices\10.4.1 RFPOs\Supporting Evidence Template v1.docx"
Set wordApp = CreateObject("word.application")
wordApp.Visible = True
Set wordDoc = wordApp.documents.Open(FilE)
newName = "THIS SMELLS"
wordDoc.CustomDocumentProperties("PO_Item").Value = newName
wordDoc.Fields.Update
wordDoc.ExportAsFixedFormat outputfilename:=filePath & newName & ".pdf",
exportformat:=wdExportFormatPDF
wordDoc.Close
wordApp.Quit
Set wordDoc = Nothing
Set wordApp = Nothing
End Sub
Run-time error '5':
Invalid procedure or argument.
Do you have a reference set to the Microsoft Word Object Library under Tools >
References? – BigBen 1 hour ago
THANKS BEN! I searched the list twice and thought that the office 16.0 reference was the correct one - it's a big list, and only after your comment went back again and found "word" was there the whole time :)
if reference to Word was there the whole time, Error 5 will also be raised if CustomDocumentProperties "PO_Item" is not added. I reproduced error 5 on that line.
Make it
wordDoc.CustomDocumentProperties.Add _
Name:="PO_Item", LinkToContent:=False, Value:=newName, _
Type:=msoPropertyTypeString
Also keep in a line
wordDoc.ExportAsFixedFormat outputfilename:=filePath & newName & ".pdf", exportformat:=wdExportFormatPDF
and it is tested and working.
Hello and thank you for your answers in advance.
I am opening a word document using excel-vba and save it under a new name.
This is actually working fine.
But problems occur if the word document with the new name is already opened!
Let's say there is a button to run the script and the user runs it the second time, and has the created file still opened. The user might change something in excel and now wants to check how the new word document would look like afterwords. He will click the button again.
It will open the template (do all changes) and try to save it, but can't because it is already opened and it might save this document with the old name (template) instead of a new file. Therefor it will overwrite and destroy the template file (got this several times during testing)!
Therefore I am in need of some proper code and a better Error-Handling. My first thought is to check if the document with the filename already exists. But it does not quite do its job:
Sub CreateWordDocument()
Dim TemplName, CurrentLocation, DocumentName, Document As String
Dim WordDoc, WordApp, OutApp As Object
With table1
TemplName = table1.Range("A1").Value 'Get selected template name
CurrentLocation = Application.ActiveWorkbook.Path 'working folder
Template = CurrentLocation + "\" + TemplName
DocumentName = .Range("A2").Value
Document = CurrentLocation + "\" + DocumentName + ".docx"
'Open Word Template
On Error Resume Next 'if Word is already running
Set WordApp = GetObject("Word.Application")
If Err.Number <> 0 Then
'Launch a new instance of Word
Err.Clear
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True 'Make the application visible to the user
End If
'if document is already opened in word than close it
'if its not possible to close it - end application to prevent any damage to the template
On Error GoTo notOpen
Set WordDoc = WordApp.Documents(DocumentName + ".docx")
On Error GoTo closeError
WordDoc.Close
notOpen:
'Open the template
Set WordDoc = WordApp.Documents.Open(Filename:=Template, ReadOnly:=False) 'Open Template
'save with new name
WordDoc.SaveAs Document
closeError:
'open a message box and tell user to close and run again.
At the current stage it just jumpes from "Set WordDoc = WordApp. ..." to notOpened. Any suggestions how to solve this issue?
Add this function:
Public Function FileIsOpen(FullFilePath As String) As Boolean
Dim ff As Long
On Error Resume Next
ff = FreeFile()
Open FullFilePath For Input Lock Read As #ff
Close ff
FileIsOpen = (Err.Number <> 0)
On Error GoTo 0
End Function
Then use in your code:
If Not FileIsOpen(DocumentName & ".docx") Then
Set WordDoc = WordApp.Documents.Open(Filename:=Template, ReadOnly:=False)
Else
'Do something else because the file is already open.
End If
The document name must be the full path to the document.
Couple of other things:
Only Document is a string, and OutApp is an object. All other variables are Variants.
Dim TemplName, CurrentLocation, DocumentName, Document As String
Dim WordDoc, WordApp, OutApp As Object
It should be:
Dim TemplName As String, CurrentLocation As String, DocumentName As String, Document As String
Dim WordDoc As Object, WordApp As Object, OutApp As Object
VBA generally uses + for addition, and & for concatenation.
DocumentName + ".docx"
would be better written as
DocumentName & ".docx"
Document is a reserved word in Word. It shouldn't cause too much problem here as the code is in Excel, but something to keep in mind.