Excel VBA to Export Selected Sheets to PDF - Stack Overflow

文章推薦指數: 80 %
投票人數:10人

I'm using the following code to export selected sheets from Excel 2010 to a single pdf file... ... My problem is that it only exports the first ... Resultsfromthe2022DeveloperSurveyarenowavailable Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore ExcelVBAtoExportSelectedSheetstoPDF AskQuestion Asked 8years,6monthsago Modified 2years,6monthsago Viewed 219ktimes 20 14 I'musingthefollowingcodetoexportselectedsheetsfromExcel2010toasinglepdffile... ThisWorkbook.Sheets(Array("Sheet1","Sheet2","Sheet3")).Select ActiveSheet.ExportAsFixedFormat_ Type:=xlTypePDF,_ Filename:="C:\temp.pdf",_ Quality:=xlQualityStandard,_ IncludeDocProperties:=True,_ IgnorePrintAreas:=False,_ OpenAfterPublish:=True Myproblemisthatitonlyexportsthefirstsheet.Anyideas? excelvbapdfexport Share Improvethisquestion Follow editedDec23,2013at20:46 PeterAlbert 16.5k44goldbadges6363silverbadges8686bronzebadges askedDec23,2013at20:39 thistledownjohnthistledownjohn 20111goldbadge22silverbadges33bronzebadges Addacomment  |  3Answers 3 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 30 OnceyouhaveSelectedagroupofsheets,youcanuseSelection Consider: Subluxation() ThisWorkbook.Sheets(Array("Sheet1","Sheet2","Sheet3")).Select Selection.ExportAsFixedFormat_ Type:=xlTypePDF,_ Filename:="C:\TestFolder\temp.pdf",_ Quality:=xlQualityStandard,_ IncludeDocProperties:=True,_ IgnorePrintAreas:=False,_ OpenAfterPublish:=True EndSub EDIT#1: Furthertestinghasreveledthatthistechniquedependsonthegroupofcellsselectedoneachworksheet.Togetacomprehensiveoutput,usesomethinglike: SubMacro1() Sheets("Sheet1").Activate ActiveSheet.UsedRange.Select Sheets("Sheet2").Activate ActiveSheet.UsedRange.Select Sheets("Sheet3").Activate ActiveSheet.UsedRange.Select ThisWorkbook.Sheets(Array("Sheet1","Sheet2","Sheet3")).Select Selection.ExportAsFixedFormatType:=xlTypePDF,Filename:=_ "C:\Users\James\Desktop\pdfmaker.pdf",Quality:=xlQualityStandard,_ IncludeDocProperties:=True,IgnorePrintAreas:=False,OpenAfterPublish:=_ True EndSub Share Improvethisanswer Follow editedDec15,2015at18:13 answeredDec23,2013at20:59 Gary'sStudentGary'sStudent 94.1k88goldbadges5656silverbadges8989bronzebadges 3 1 thisonlyprintsablanksheetforme.notsurewhy? – HattrickNZ Jul24,2014at22:56 1 UsingSelectiononlyseemstoexportablanksheetinExcel2013.TheuseofActiveSheetasseeninASP8811andHattrickNZ'sanswersdidworkforus. – Adrian Jun10,2015at10:08 yougeta+1foragoodanswerbutalsoforthenameofyoursub.that'sveryclever. – DexterWhelan Jan30,2017at12:03 Addacomment  |  8 I'mprettymixeduponthis.IamalsorunningExcel2010.ItriedsavingtwosheetsasasinglePDFusing: ThisWorkbook.Sheets(Array(1,2)).Select **Selection**.ExportAsFixedFormatxlTypePDF,FileName&".pdf",,,False butIgotnothingbutblankpages.Itsavedbothsheets,butnothingonthem.Itwasn'tuntilIused: ThisWorkbook.Sheets(Array(1,2)).Select **ActiveSheet**.ExportAsFixedFormatxlTypePDF,FileName&".pdf",,,False thatIgotasinglePDFfilewithbothsheets. ItriedmanuallysavingthesetwopagesusingSelectionintheOptionsdialogtosavethetwosheetsIhadselected,butgotblankpages.WhenItriedtheActiveSheet(s)option,IgotwhatIwanted.WhenIrecordedthisasamacro,ExcelusedActiveSheetwhenitsuccessfullypublishedthePDF.Whatgives? Share Improvethisanswer Follow answeredApr14,2014at16:49 asp8811asp8811 77388silverbadges1313bronzebadges 3 whatisFileNameequalto?canFileNameincludeapath?myref – HattrickNZ Jul24,2014at23:35 IamnowgettinganerrorwiththisArray(1,2)whatisthismeanttobe?itslikeitwillonlyaccept1worksheetname? – HattrickNZ Jul24,2014at23:47 Sorrythisisafterthefact.Ihaven'tloggedoninawhile.Filenameshouldincludethefilepathtothelocationyouwanttosavetoaswellasthefilename. – asp8811 Sep8,2014at13:46 Addacomment  |  4 thisiswhaticameupwithasiwashavingissueswith@asp8811answer(maybemyowndifficulties) 'thiswilldotheputthefirst2sheetsinapdf 'Noteeachwsshouldbecontrolledwithpagebreaksforprintingwhichisabitfiddly 'thiswillexplicitlyputthepdfinthecurrentdir Subluxation2() DimFilenameAsString Filename="temp201" DimshtAry() ReDimshtAry(1)'thisisanarrayoflength2 Fori=1To2 shtAry(i-1)=Sheets(i).Name Debug.PrintSheets(i).Name Nexti Sheets(shtAry).Select Debug.PrintThisWorkbook.Path&"\" ActiveSheet.ExportAsFixedFormatxlTypePDF,ThisWorkbook.Path&"/"&Filename&".pdf",,,False EndSub Share Improvethisanswer Follow answeredJul25,2014at1:01 HattrickNZHattrickNZ 3,7951414goldbadges4747silverbadges9191bronzebadges 1 Mineonlyworkswiththefirsttwosheetsbecausethat'swhatIwasgoingforinmycode.Myanswerwasn'treallyananswer,moreofaclarificationaboutusingActiveSheetinsteadofSelectionbecauseIdidn'thavethereputationtocommentatthetime.Yoursolutionismuchbetterforusingmultiplesheets. – asp8811 Sep8,2014at13:55 Addacomment  |  Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedexcelvbapdfexportoraskyourownquestion. TheOverflowBlog CelebratingtheStackExchangesitesthatturnedtenyearsoldinSpring2022  GitHubCopilotishere.Butwhat’stheprice?(Ep.457) FeaturedonMeta Testingnewtrafficmanagementtool Duplicatedvotesarebeingcleanedup Trending:Anewanswersortingoption AskWizardTestResultsandNextSteps Shouldweburninatethe[hyphen]tag? Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Linked -1 PrintingbyVBAinexcel-printonlyPagesthatiwant 2 ExportExcelworksheetstoindividualpdfsusingVBAcode 2 Exportexceltextasanimagefile 2 ExportDifferentSheetsinoneexcelfiletodifferentpdffiles? 1 SavingMultipleRangesontwodifferentsheetstoPDFusingVBA -1 ConvertingExcelDocumenttoPDFusingVBA 0 Howtoexportaspecificpagefromasinglesheettopdf? 0 UsingVBAtoprinttoPDFexistingmacro 1 Forlooppreservingpreviousiteration 0 MAcro:choseafiletomodify,modifyeachsheet,exportxlsxandpdf Seemorelinkedquestions Related 2087 HowdoIcreateanExcel(.XLSand.XLSX)fileinC#withoutinstallingMicrosoftOffice? 2485 Doa"gitexport"(like"svnexport")? 1317 RecommendedwaytoembedPDFinHTML? 1415 ProperMIMEmediatypeforPDFfiles 605 HowtoavoidusingSelectinExcelVBA 1 ExcelVBAExportMultiplesheetstoPDF 0 ConvertonlyfewcolumnsfromExceltoPDF HotNetworkQuestions Novelaboutincompetentspacepirates Howcanweexperimentallyconfirmthatatoms/moleculesinasolidactually"move"? Diseasethatrapidlykillsandreplacescells-severityofsymptoms BalancingCommandwhiletakingintoaccountlanguages Whydowe"normal-order"insteadofjustsubtractingoffvacuumenergy? Howaretheprojectionsofthisplotmade? HowcanIcleanthesewheels? Istheresuchthingas"administratorroot"? Gettingridof"ThefollowingpackageswillbeDOWNGRADED" Howwouldthefightingofmedievalstylewarsbealteredbythepresenceofapredatorspecies? Howto(safely)permanentlyturnoffnaturalgas? Whatisthenameofthejobwhorepresentsafamilytrusttomanagefixedassets Isthisproofthatmasslessobjectscannotbecharged? What'sthetypicaltemperatureofareactorcoreinanuclearthermalrocket? IhavewrittenonemathematicalpaperwhichIwanttopublish,doIneedtogiveprofessorco-authorship? Ascifibookcontaininganartificially-madeworldwithweirdcentaurs CreatingacampaignthatendswithaTPKbydesign Non-asciicharactersinRewriteRule:alpha: Docountries(withruleoflaw)existwhereacourtcanrequirethelegislaturetovoteonalawinordertoclearambiguities? HowcanItellmybossthatmyproductivityislowduetoaconflictwithacoworker,withoutblamingthecoworker? visitorvisaforCanada:proofofrelationshipforinvitingfamilyfriend What’sthedifferencebetween“Bandit”and“Bogey” CanallLEGOLococharactersberecreatedinreallife? HowcanIremovealluvlayersbutthelastoneandrenameitonmultipleobjects? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-vb Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?