Error using ExportAsFixedFormat command - vba

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 :)

Related

Macros formatting worksheet as xlsm instead of pdf

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...

Automation Error - The Object Invoked has Disconnected from It Clients during autofilter

Ok, I know there are many posts about this but so far none of them have a solution that seems to work for me.
I ran across this for the first time a week ago and have created a very simple program to try and figure out what is going on. I have resorted to hand typing all this (I usually start with an old macro and modify it or copy and past code pieces); I have made my own data file just in case there was something weird with the file I am planning to use as the input; and it still errors out.
I have other macros that are doing the exact same processes and they still work fine. This is driving me insane. The code below crashes on the Autofilter line.
Sub Fred()
Dim strFileToOpen As String
Dim wbHL7 As Workbook
strFileToOpen = Application.GetOpenFilename(Title:="Please select the Invoice file.", FileFilter:="Excel Files *.xls* (*.xls*),")
If strFileToOpen = "False" Then
MsgBox "No file selected.", vbExclamation, "Sorry!"
Exit Sub
Else
Set wbHL7 = Workbooks.Open(Filename:=strFileToOpen)
End If
rCnt = Cells(Rows.Count, 1).End(xlUp).Row
ActiveSheet.Range("A1:K" & rCnt).AutoFilter Field:=11, Criteria1:=0, Operator:=xlFilterValues
ActiveSheet.Range("A1:K" & rCnt).Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
ActiveSheet.AutoFilterMode = False
End Sub
Many of the other posts hint that there might be an issue with my actual system such as compatibility things, but then why are the other macros still working? By the way, once it does this, it basically locks up everything to do with Excel and I have to open the Task Manager to kill the process. I am using Windows 7 and Office 2013.
Edit:
I just want to add that if I record an autofilter macro in the same book as the data, it works fine.
You have an error in your code. The criteria needs to be a string. If you look carefully at the recorded macro you'll see that it too uses a string.
Change your autofilter line to the following and it should work:
ActiveSheet.Range("A1:K" & rCnt).AutoFilter Field:=11, Criteria1:="=0", Operator:=xlFilterValues

Automatic refreshment of Excel DDE RTD

I'm subscribed to a RTD financial application with the option to export real time data to Excel via DDE. So, using the DDE copy/paste app option, I've created a Excel table with real time DDE financial data. Cells actually contains DDE formulas. Now I open, refresh and save table manually, but what I need is a solution that will open, refresh the data, save and close this excel table automatically.
I didn't now how to attach the file, so here is a screenshot of it.
My Excel DDE file
Since I'm new to vba and vbscript, I was searching internet for a solution but without any success, especially not for automatic update (refreshment) of the DDE data.
What I've been doing for the past few days, was searching, trying and customising different kind of vba macros and vbscripts, and today I'm completely lost and confused.
I have tried bunch of suggested solution, even yours
Refresh data and exit with saving Macro Excel
and On workbook open, Excel Macro to refresh all data connections sheets and pivot tables and then export the pivot to csv but in my case they don't work.
Any solution, reference, code example will be greatly appreciated.
Kindly try the below one and
be careful when using
Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic
this sets the entire excel application to calculate formula's either automatically or manually. If you use
Application.Calculation = xlCalculationManual
you'll notice your automatic formulas no longer work.
Thanks for the reply #mulla, but this doesn't work. In vbscript I get runtime error and in vba nothing happens (does not affect refreshment). The same thing is for the Worksheet.Calculate.
Than I recorded a macro upon manual update of the links (data) in order to inspect how Excel proceed update and this actually works, but not all the time. If I open Workbook manually and I keep it opened than whole export works perfectly since the data is constantly refreshed (not what I need). In case when the Workbook is opened via vbscript only (what I need), as you can see in the output below some of the values are exported successfully (for the faster refreshment I believe) and some are #N/A (for the slower refreshment). All the data is refreshed every second, except upon opening the file where successfully exported values are refreshed instantly and #N/A values need few seconds (2-3s) to be refreshed.
Recorder macro uses ActiveWorkbook.UpdateLink as follows (the code below is for the first row, but the same logic is used and for the rest of the rows):
Sub PriceUpdate()
ActiveWorkbook.UpdateLinks = xlUpdateLinksAlways
ActiveWorkbook.UpdateLink Name:= _
"vegadde|VEGA!897789,148,1#""1,\""12,0,0\"""",1", Type:=xlOLELinks
ActiveWorkbook.UpdateLink Name:= _
"vegadde|VEGA!897789,148,1#""1,\""12,0,0\"""",3", Type:=xlOLELinks
ActiveWorkbook.UpdateLink Name:= _
"vegadde|VEGA!897789,148,1#""1,\""12,0,0\"""",4", Type:=xlOLELinks
...
End Sub
Then I use vbscript to call the macro and export data in CSV comma delimited file with timestamp name:
Option Explicit
Dim objExcel, objBook, objSheet
Set objExcel = CreateObject("Excel.Application")
Set objBook = objExcel.Workbooks.Open ("d:\exptest\exptest.xlsm", 0, False)
'Set objSheet = objBook.Worksheets.Item(1)
objExcel.DisplayAlerts = False
objExcel.Run "PriceUpdate"
WScript.Sleep 5000 ' Delay in order to update links
objBook.SaveAs "d:\exptest\" & Year(Now) & "." & Month(Now) & "." & Day(Now) & "_" & Hour(Now) & "-" & Minute(Now) & ".txt",6
objBook.Close False
objExcel.DisplayAlerts = True
objExcel.Quit
'Set objSheet = Nothing
Set objBook = Nothing
Set objExcel = Nothing
And what I get is the following uotput:
Inst,Price,Datetime
USD,1.1015,7/22/2016 12:48
GBP,#N/A,#N/A
CHF,#N/A,#N/A
SEK,9.4962,7/22/2016 12:48
NOK,#N/A,#N/A
JPY,#N/A,#N/A
DKK,#N/A,#N/A
CAD,#N/A,#N/A
AUD,1.47395,7/22/2016 12:48
RUB,71.0082,7/22/2016 12:48
I'm struggling to learn Excel logic behind different updates in order to solve my problem and to get desired solution, but with no success.
And this is only a test file with 22 links. The real one has 482 links that need to be updated.
Marjan. Not sure if this is still a problem for you, but I ran into a similar problem with refreshing RTD data in a closed Excel workbook and seem to have found a solution. As you mentioned, when you open the workbook, the data refreshes automatically (with some of the more complex data points taking 2-3 sec). The problem is, you don't want to have to constantly manually open a workbook to refresh data. And I've found that the data fails to refresh with methods like RTD.RefreshData called to a closed workbook.
So to fix this, I created a vba module that simply opens the workbook, refreshes it, pauses for a second (you may need 2-3 more seconds for all data to update) and then saves and closes the workbook. This method is called recursively. Essentially this does the work of constantly opening and closing the workbook, while delaying briefly so that the RTD data can refresh. So far, this is able to provide refreshed RTD data successfully (although there is an inherent slight delay of a few seconds). Here's the basis of my code:
Sub refreshXLS()
Path = "workbook.xlsm" 'the workbook path you want to refresh
Workbooks.Open Path
ActiveWorkbook.RefreshAll
Application.OnTime Now() + TimeValue("00:00:01"), "closeActive"
End Sub
Sub closeActive()
ActiveWorkbook.Save
ActiveWorkbook.Close
refreshXLS
End Sub
Hope this helps if you still wish to solve this problem!

Inserting, searching, copying, pasting across 2 spreadsheets in Excel

I thought I'd be able to figure this out based off an analysis of similar code we had written for something else, but code isn't my forte.
Diving into VBA without guidance has proved to be too daunting for me to proceed.
Forgive my terminology if I use the wrong language, I'm happy to learn and be corrected.
This shouldn't be difficult for someone that knows what they're doing, I just don't at all.
I'm trying to create a macro enabled workbook that does the following:
Open "Data.csv" from a folder called "Data" in the same directory as the macro. We'll call this workbook A - wbA.
Insert a column on wbA after Column C titled "Group Image Name." This Column D is where we want data to end up.
Open "Groups.csv" from a folder called "Groups" in the same directory as the macro. We'll call this workbook B - wkB.
(This next part needs to be a loop that starts at C1 on wbA and proceeds down the column until the end of the spreadsheet)
Copy value from selected cell in Column C on wbA
Search Column C on wbB for copied value. When found, move selection over to corresponding cell in Column A. (If C2, then A2)
Copy contents of the column A value from wbB to column D cell on wbA that corresponds to the original starting point on wbA.
Basically in plain language: Search for Column C contents from wbA on Column C of wbB. When found, move to Column A of same cell # on wbB, copy contents, and paste into cell # of Column D on wbA that corresponds to cell # of starting point from Column C.
I hope that's clear; please feel free to ask for more details if necessary. Thanks for anyone's help in advance!
Here is my terrible code I'm working with at the moment:
Sub OpenDataAddGroupImageTitleColumn()
ChDir "C:\[RealCodeHasCorrectFilepath..]\Desktop\TEST"
Workbooks.Open Filename:="C:\[RealCodeHasCorrectFilepath..]\Desktop\TEST\DATA.csv"
Columns("D:D").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Cells.Select
Cells.EntireColumn.AutoFit
Range("D1").Select
ActiveCell.FormulaR1C1 = "Group Image Title"
Range("C2").Select
'Variables for storing Row, Column Location, and Value here
Dim GROUPNAME As String
Dim RowLocationX As Long
Dim ColumnLocationZ As Integer
GROUPNAME = ActiveCell.Value
RowLocationX = ActiveCell.Row
ColumnLocationZ = ActiveCell.Column
Workbooks.Open Filename:="C:\[RealCodeHasCorrectFilepath..]\Desktop\GROUPS.csv"
Columns("C:C").Select
Selection.Find(What:="GROUPNAME", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
End Sub
The current snag I can't figure out after much googling is this: Is it possible to search for my variable GROUPNAME using the Find/Replace feature? Or should I be taking a different approach using something involving copying to clipboard?
The first problems that I see are:
1) You don't put functions in the middle of sub routines. If you want a function, you put it on its own as such:
Sub MySub()
'Do Stuff
x = myFunction()
debug.print x
End Sub
Function MyFunction() As String
'Do Stuff
MyFunction = "Test"
End Function
2) The code you have provided won't compile for reason 1 and also because you have ended the Sub with "End Function" instead of End Sub. Try running the code and you will get error messages. Then you can research the error message and try to fix it. Further, if you don't get error messages, you can step through the code to make sure it is working the way you intend it to.
3) The very first line isn't going to work. You need to use the ENTIRE path of the file, even if it is in the same folder as the file you currently have open. There are ways to get the directory of the file you currently have open (google will surely show you many of them), and you could just append the filename to the directory of the file you have open.
4) You want a loop, but you haven't put in any looping structions. Google "Excel VBA loop through cells" and you can find many examples to use.
5) I think the biggest issue that you are having is that you are overwhelmed because you are trying to do everything all at once. I would suggest solving one problem at a time and then putting the code together. For instance, you want to open two files. Start by writing code just to open one file. Then try to get a value out of the file into the open workbook. Then open another file. Then get data out of that file. Then test looping through cells in the current workbook and checking for desired criteria and pasting the results if they match. Then combine all of these things into coherent code.
Nobody writes efficient code the first time they try, so even if you end up with really long code that isn't efficient, you'll learn a lot and have something. Even experienced programmers can get stuck or write code that doesn't work the first or even tenth time. If you get stuck, ask a specific question about a specific error message or specific issue that you can't resolve.

Excel print to PDF - not working without error code returned

I have encountered a very strange problem with a previously working piece of code that was discussed here a while ago.
This code used to do exactly what it should: save the part of the sheet inside the print area as a PDF file. However, after changing the code in another module of the same Excel file, this code does not execute anymore, without returning any error message at all.
It would be great if someone could test that code on their machine and tell me whether or not it works or at least returns any error at all? Code is below; I can provide more code from other modules in the file as well as screenshots, if necessary. Many thanks for your help!
Sub Invoice_to_PDF()
'Saves the invoice print area to a PDF file
Dim fp As String
Dim wb As Workbook
Dim ws As Worksheet
fp = "C:\Users\Matthias\Desktop\NewInvoice.pdf"
Set wb = ActiveWorkbook
Set ws = Worksheets("Invoice")
ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fp, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
Code works great, no error is returned. Tested on Excel 2010 with a fresh file containing only this method and few data.