Macros formatting worksheet as xlsm instead of pdf - vba

I have created a macro that once a button is clicked on a worksheet a new Outlook email is generated with the worksheet as an attachment.
When recording the macro and then looking at the format in the code it is saying pdf. When I trial the button the attachment is formatted as a xlsm.
Sub email()
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\ROANDE~1\AppData\Local\Temp\Purchase Order Turkey MASTER Version 2.pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Application.Dialogs(xlDialogSendMail).Show
End Sub
I'm completely new to VBA.

Nice try. :) but...
Application.Dialogs(xlDialogSendMail).Show
...is the VBA equivalent of clicking File → Send (or Share in some versions), which opens an e-mail message in Microsoft Outlook with the current workbook attached.
You have 2 lines of code there. The first line exports the Active Workbook to a PDF file located at C:\Users\ROANDE~1\AppData\Local\Temp\Purchase Order Turkey MASTER Version 2.pdf.
That is unrelated to the next line (a hint being a fact that the 2nd line doesn't mention a filename, variable, etc.).
I'm always been a fan of the beginner technique of recording a macro doing what you want VBA to do, and then adjust as required, but some things do get missed (or ignored) by the Macro Recorder, probably like in this case.
1st, can you please confirm that the PDF exists (at the path above) and has the correct data that you want to email? Also which version of Excel are you using? (next time add the tag for your version when posting your question, like excel-2016 etc.)
After that's steps verified working, we can move on to emailing the PDF...

Related

Excel pdf exporting - Run-time error '5" in Excel VBA

I've developed code that has been functional for the last 3 years on multiple company computers, all running Windows 7 and Office 2007. A new round of lease renewals has occurred and one of my employees has been given a machine running Windows 10 and Office 2007. We are all running different versions of Acrobat Pro.
I am having a problem with a macro that's in my Excel workbook that outputs a PDF whenever a user clicks on a button embedded in the sheet. Basically, the sequence is:
User presses button.
Spreadsheet recalculates (F9).
User is prompted where to save the file (filename is already prepopulated based upon a cell in the sheet).
User selects save and pdf is saved.
Pop-up box prompts user whether the new pdf should be printed to the local printer. If "yes", print, else don't.
End sequence.
Here's the code:
'Code for creating the PDF document and subsequently displaying it
Dim fnamePDF As String
With ActiveSheet
fnamePDF = .Range("H11").Value
.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ActiveWorkbook.Path & "\" & fnamePDF, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End With
Any help would be most appreciated.

Error using ExportAsFixedFormat command

I am trying to debug some code containing an ExportAsFixedFormat that is causing an "Automation error the object invoked has disconnected from its clients." error message. I am running in 2013 so don't need the PDF/XPS add-in and the function works elsewhere in the workbook. It seems to have something to do with the page I am trying to make the PDF out of. While the main macro is longer, I am having the same error occur when I use this simple piece of code:
Sub NewAssetScreen()
Sheets("New Asset").Select
Sheets("New Asset").Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Quality:=xlQualityStandard, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
Sheets("New Asset").Select
Range("A1").Select
End Sub
However if I run the macro with a different worksheet name it works fine. The selection part seems to be ok - ie will work with that worksheet name but it is just the ExportAsFixedFormat command that won't work on the page.
Any insights as to why this might be the case?
Thanks in advance.
Nic
Check page breaks and other things specific to that worksheet.
Try using Sheets("New Asset").ExportAsFixedFormat instead of ActiveSheet.
Lastly try copying and pasting the contents of the New Asset sheet to a new sheet and delete the old one.
Make sure there are no "/" or other non file name characters in any of the worksheet fields you are using. My issue occured when printing 100 worksheets, 2 would fail. After much frustration I found the "/" in a heading I was using for the name the file :)

Excel VBA code is causing my worksheets to appear as jargon

I currently am using a VBA macro that I found here on stack over flow. The problem is when I run it it saves all the data into a separate excel sheet but when i open it it appears as "jargon" in other words unreadable type. This is the "Save code"
'Save the new workbook, and close it
wb.SaveAs ThisWorkbook.Path & "\test" & WorkbookCounter
wb.Close
The way I am currently running the code is that it separates my excel sheets into different spread sheets by rows of 250. Everything works but when I open the saved documents it says that this file format is unacceptable to Excel. Then I try importing it and I get an error. Here is a snap shot of the way it appears in my screen. Also here is the file name: built.list\test.xls39
Your workbook counter always ends in a number, Windows and Excel use the file extension to determine file-type, so an '.xls39' file is unrecognisable. Try:
wb.SaveAs _
Filename:=ThisWorkbook.Path & "\test" & WorkbookCounter & ".xls" _
FileFormat:=XlFileFormat.xlExcel8
'Use xlOpenXMLWorkbook for the .xlsx format
(Use space followed by underscore to separate lines in VBA)
Or make sure WorkbookCounter ends in .xls and not a number.
(Edit: For other formats, please look in the References dialog in Excel VBA Editor)

Using vba to copy the contents of a word document into another word document

I haven't used VB for years, so please forgive me if this turns out to be obvious. I'm trying to write a word vba macro for use in a template which will display a userform and then import the contents of fileA.docx, fileB.docx, or fileC.docx depending on the userform. (After that I'm going to use bookmarks to fill in some form data, I don't know if that's relevant). Files A, B, and C will contain text with some basic formatting such as lists, but nothing fancy.
The solutions I've seen online can copy the contents of file to a new file, but ideally I would like to import the entirety of one of those files into the new, currently unnamed file that I'm getting from the template. I think where I'm running into problems is with switching the selection to one of those files, and then back to the new unnamed document, though I could use a hand to make sure I'm copying correctly as well.
Update: I was making things too hard, though the answers here got me pointed in the right direction (thanks!). In the end I just did
ThisDocument.Activate
Selection.InsertFile("fileA")
which gives me the raw dump of everything that I wanted.
Using commands such as these you can switch between which Document you're using and copy and paste elements:
ThisDocument.Activate 'Sets the main document active
Documents("Name.doc").Activate 'Activates another document
You can insert, copy and paste things in and out of documents using copy commands.
ThisDocument.Range.InsertAfter("String") 'Insert text
Selection.WholeStory 'Select whole document
Selection.Expand wdParagraph 'Expands your selection to current paragraph
Selection.Copy 'Copy your selection
Documents("name.doc").Activate 'Activate the other document
Selection.EndKey wdStory 'Move to end of document
Selection.PasteAndFormat wdPasteDefault 'Pastes in the content
You can then go and format such, or copy and paste them with original formatting from before.
Here is a significant improvement (I think) you will want to incorporate because it:
does not use the clipboard and thus does not make your macro vulnerable to the user changing the contents of the clipboard while your macro is running
does not use a file and thus greatly improve the speed by eliminating I/O and eliminates the potential of having to deal with file system security/permissions, etc. Please do not use .InsertFile() if you are looping through documents you will slow yourself down. Use it once, at the end -only if you have to. The example below shows how to accomplish the same result without using .InsertFile()
The idea is to transfer some portion of text found in 1 source document, to a destination document that is different than the source, and keep the source formatting.
To accomplish the above (skipping the code to open documents):
For Each oTable In oDoc_Source
'the above could have been anything that returns a Range object
'such as: ActiveDocument.Content.Find.Execute ....
'...
'logic here to identify the table, or text, you are looking for
'...
'I can't believe the MS Dev Center folks could only think
'of .InsertFile(), which is the last resort I would go for,
'especially if your code runs on a web server [concurrent web requests]!
'SAFEST
'(no user interference on clipboard possible, no need to deal with file i/o and permissions)
'you need a reference to Document.Content,
'as the act of obtaining a reference "un-collapses" the range, so the below 3 lines must be in that order.
Set oRange = oDoc_DestinationDoc.Content
oRange.Collapse Direction:=wdCollapseEnd
oRange.FormattedText = oTable.Range
'BRUTE, AND PRONE TO RANDOM ERRORS AND HANGS DUE TO USER INTERFERENCE WITH CLIPBOARD
'find a way to implement WIHTOUT using the CLIPBOARD altogether to copy the below range object
'it will be easier for PC users to use the clipboard while the macro runs
'and it will probably be safer for the output of this macro to remain uncorrupted
'oTable.Range.Copy
'Set oRange = oDoc_DestinationDoc.Content
'oRange.Collapse Direction:=wdCollapseEnd
'oRange.Paste
'THE BELOW DOES NOT WORK
' '1) - cannot add a range from another document
' 'adds only text, not the formats and not the table layout
' oTable.Range.TextRetrievalMode.IncludeFieldCodes = True
' oTable.Range.TextRetrievalMode.IncludeHiddenText = True
' oDoc_DestinationDoc.Content.InsertAfter oTable.Range
'
' '2) - cannot add a range from another document
' oDoc_DestinationDoc.Content.Tables.Add oTable.Range, iRowMax, iColMax
'
' '3) - only puts in plain text, and it replaces the range without the .Collapse call
' oDoc_DestinationDoc.Content.Text = oTable.Range
Record a macro...
start in the source document
press ctrl-a to select everything
press ctrl-c to copy it to the clipboard
switch to the target document
press ctrl-v to paste into the document
stop recording
or (assuming word 2007 or later)
start in the target document with the source document closed
on the ribbon click insert > object > Text from file...
navigate to the source document
click the insert button
stop recording
I prefer the second version so I should have put it first
I was doing the same thing, tried to select the other document, copy and paste. But it didn't worked (I received an error probably because some other application was using the clipboard, but I am not sure.). So I did a little search and found the perfect solution on Microsoft Dev Center.
https://msdn.microsoft.com/en-us/vba/word-vba/articles/selection-insertfile-method-word
Selection.Collapse Direction:=wdCollapseEnd
Selection.InsertFile FileName:="C:\TEST.DOC"
'set current doc name and path
Dim docName As String: docName = ActiveDocument.name
Dim filepath As String: filepath = ActiveDocument.Path
'create a new file
Documents.Add
'get the path of a current file
ChangeFileOpenDirectory filepath
'insert content of current file to newly created doc
Selection.InsertFile _
FileName:=docName, _
Range:="", _
ConfirmConversions:=False, _
Link:=False, _
Attachment:=False
'open prompt to save a new file
With Dialogs(wdDialogFileSaveAs)
.name = docName & "-copy"
.Show
End With

Excel VBA: create a word document with an excel file embedded in it

I am currently using a basic macro to create a formatted word document using form information entered into an excel sheet.
However, I would also like to create a new excel sheet using the same macro, and embed that sheet into the word document (not as a table, but as a file).
If someone can explain the general approach that ought to be taken, I can probably figure it out. Thanks kindly.
Based on the Word macro recorder you could insert Excel file into Word document something like this way:
Selection.InlineShapes.AddOLEObject ClassType:="Excel.Sheet.12", _
FileName:="C:\Users\Your Name\Documents\Albums.xlsx", _
LinkToFile:=True, DisplayAsIcon:=True, _
IconFileName:="C:\Windows\Installer\{90140000-003D-0000-0000-0000000FF1CE}\xlicons.exe", _
IconIndex:=1, IconLabel:="Albums.xlsx"