How do i save as pdf via VBA - vba

I have a code, where I want to:
Save Masterfile (current active workbook),
amend the workbook and delete sheets,
then save separate copies of the edited workbook
as an Excel sheet and a PDF file.
The problem I have here is that the code saves the PDF file as the original Masterfile even after I have tried to activate the edited Excel file. Any help here? Would really appreciate any advice! Code below:
ActiveWorkbook.Save
Sheets("Inventory").Select
Cells.Select
Selection.Copy
Cells.Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.DisplayAlerts = False
Sheets("May").Select
Cells.Select
Selection.Copy
Cells.Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
Sheets("Macro").Select
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = False
Sheets("Oct").Select
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = False
Sheets("Inventory").Select
Range("A1").Select
Sheets("Inventory").Cells.Interior.ColorIndex = 0
ChDir "G:\9Fixed\Posi\2016\Inventory"
ActiveWorkbook.SaveAs Filename:= _
"G:\9Fixed\Posi\2016\Inventory\Asia Fixed - " & Format(Date, "dd mmm") & ".xls", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
Application.DisplayAlerts = False
'ActiveWorkbook.ExclusiveAccess
Application.DisplayAlerts = True
Workbooks("Asia - " & Format(Date, "dd mmm") & ".xls").Activate
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"G:\9Fixed Income\Positions\2016\Inventory\Asia Fixed Income - " & Format(Date, "dd mmm") & ".pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False

I could not reproduce the issue you were having.
Here is my 'test' code, using a workbook with 4 sheets and information in cells(1,1), one sheet named "May" --- which is deleted, and the new file does not have "May" and the pdf does not either.
I moved the saveas code towards the top of the file. Maybe that will fix your issue, but I don't believe it will.
Option Explicit
Sub SaveCopies()
Dim c_OUTPUTDIR As String
Dim sFileName As String
Dim fso As Object ' Used to handle paths, filenames, etc.
Set fso = CreateObject("Scripting.FileSystemObject")
c_OUTPUTDIR = "C:\temp\"
' Save the master copy.
ActiveWorkbook.Save
' Generate new name for file.
sFileName = fso.GetBaseName(ActiveWorkbook.FullName) & "_" & Format(Date, "dd mmm")
' Save new working file.
ActiveWorkbook.SaveAs Filename:= _
c_OUTPUTDIR & sFileName & ".xls", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
' Make changes to working file.
Application.DisplayAlerts = False
ActiveWorkbook.Sheets("May").Delete
Application.DisplayAlerts = True
' Save the changes.
ActiveWorkbook.Save
' Save a PDF of the file.
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
c_OUTPUTDIR & sFileName & ".pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub

Related

How to save a new excel worksheet to variable location based on a cell value

I try to set up a code that will save a excelworksheet in a workbook as a PDF and will extract one other worksheet and saves that one under a different name in the same location. atm my code works except for the part that it saves the file not always to the right location.
I use an excel formula to get the right filepath in cell "Dimensionering!I8". I save the worksheet in the same location as the workbook is allready saved.
In the second part of the code I copy a worksheet to a new workbook so I linked the filepath from the worksheet 'dimensionering' to the worksheet 'offertetekst'.
Sub SAVE()
Dim filename As String
Dim filename1 As String
filename = Range("Dimensionering!C8")
Sheets("offerte stuklijst").Select
ActiveSheet.Range("$A$18:$A$1731").AutoFilter Field:=1, Criteria1:="1"
ActiveWindow.SmallScroll Down:=6
Chdir Range("Dimensionering!I8")
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:=filename & ".pdf", Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
filename1 = Range("Offerte_tekst!E1491")
Sheets("Offerte_tekst").Select
Sheets("Offerte_tekst").Copy
Chdir Range("Offerte_tekst!E1492")
ActiveWorkbook.SaveAs filename:=filename1 & ".xlsx" _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End Sub
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=Sheets("Dimensionering").Range("I8").Value & "\" & filename & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
ActiveWorkbook.SaveAs filename:=Sheets("Offerte_tekst").Range("E1492").Value & "\" & filename1 & ".xlsx" _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
This assumes you don't have backslash in your path cell Dimensionering!I8

vArray if else macro

I am trying to create a macro the adds different pages to a pdf based on a check box status. This is what I currently have.
Sub ToyotaMO()
'
' ToyotaMO Macro
'
Sheets("TC").Visible = True
Sheets("BS").Visible = True
Sheets("ToyotaMO").Activate
If Sheets("ACM").OLEObjects("Toyota").Object.Value = True Then
vArray = Array("ToyotaMO", "TC", "BS")
Else
vArray = Array("Proposal", "TC")
End If
ThisWorkbook.Sheets(vArray).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & "\" & ActiveSheet.Range("C5").Value & " Toyota Material Only ACM Proposal" & Format(Date, " MMDDYY") & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
Sheets("ToyotaMO").Activate
Range("A1").Select
Sheets("TC").Visible = False
Sheets("BS").Visible = False
Sheets("ACM").Select
Range("B1").Select
End Sub
The macro works on all the other forms the only difference is I need to add worksheet "BS" to the PDF if the checkbox is checked. VBA always stalls at ThisWorkbook.Sheets(vArray).Select.
Any help is greatly appreciated
Try the following, this will loop through your array and do what you expect:
Sub ToyotaMO()
'
' ToyotaMO Macro
'
Sheets("TC").Visible = True
Sheets("BS").Visible = True
Sheets("ToyotaMO").Activate
If Sheets("ACM").OLEObjects("Toyota").Object.Value = True Then
vArray = Array("ToyotaMO", "TC", "BS")
Else
vArray = Array("Proposal", "TC")
End If
For i = LBound(vArray) To UBound(vArray)
ThisWorkbook.Sheets(vArray(i)).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & "\" & ActiveSheet.Range("C5").Value & " Toyota Material Only ACM Proposal" & Format(Date, " MMDDYY") & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
Sheets("ToyotaMO").Activate
Range("A1").Select
Sheets("TC").Visible = False
Sheets("BS").Visible = False
Sheets("ACM").Select
Range("B1").Select
Next i
End Sub

Deleting a File using VBA

I currently have a code to delete files in a userform. I enter a reference and this in term populates to a sheet and all the calculations are worked out.
What I am trying to do is delete the old existing document and then save a new copy with the word "CLOSED" in the title. I feel this code should work but cannot see why it is not finding the specified file.
Sub CloseDoc()
Dim FSO
Dim sFile As String
sFile = "M:\Documents\" & Range("B3").Text & " - " & Range("B14").Text & ".xlsx"
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(sFile) Then
FSO.DeleteFile sFile, True
MsgBox "Deleted The File Successfully, Ready to update with CLOSED information", vbInformation, "Done!"
Else
MsgBox "Specified File Not Found", vbInformation, "Not Found!"
End If
Sheets("ITC").Copy
Range("A1:B54").Select
Application.CutCopyMode = False
Selection.Copy
ActiveWindow.SmallScroll Down:=-60
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
'Save Document to Dir
ActiveWorkbook.SaveAs Filename:= _
"M:\Documents\" & Range("B3").Text & " - " & Range("B14").Text & " - CLOSED" & " .xlsx", FileFormat _
:=xlOpenXMLWorkbook, CreateBackup:=False
ActiveWorkbook.Close
End Sub

Run- Time Error 1004 : Application-defined or object-defined error

In summary, the code below copies all the information on a sheet and pastes the information on a new excel sheet while keeping the formatting. That document is then saved with the naming convention of the active sheet name and the current date. This sheet is saved in two places and then closes itself. When I run the code all the steps occur but the document does not save into the two folders and the error message pops up and stops the code there. Can you please check out my code and see why it does not work? Thank you in advance!
Sub SaveXLST()
'
' SaveXLST Macro
'
Dim monthVal As Integer
Dim mVal As String
Dim dayVal As Integer
Dim dVal As String
Dim yearVal As Integer
Dim yVal As String
monthVal = Month(Date)
dayVal = Day(Date)
yearVal = Year(Date)
If monthVal < 10 Then
mVal = "0" & monthVal
Else
mVal = "" & monthVal
End If
If dayVal < 10 Then
dVal = "0" & dayVal
Else
dVal = "" & dayVal
End If
Cells.Select
Range("A9").Activate
Application.CutCopyMode = False
Selection.Copy
Workbooks.Add
Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone _
, SkipBlanks:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveWindow.SmallScroll Down:=-12
Application.CutCopyMode = False
ChDir "N:\D\IG\C\~ P"
ActiveWorkbook.SaveAs Filename:= _
"N:\D\IG\C\~P\T" & "-" & yearVal & "." & mVal & "." & dVal, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
ChDir "N:\D\IG\C\T"
ActiveWorkbook.SaveAs Filename:= _
"N:\D\IG\C\T\T" & "-" & yearVal & "." & mVal & "." & dVal, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
ActiveWindow.Close
End Sub
Here is your code with some minor adjustments / improvements (including the ones suggested by #ScottCraner and #Charlie in their comments).
Option Explicit
Sub SaveXLST()
'
' SaveXLST Macro
'
Dim monthVal As Integer
Dim dayVal As Integer
Dim yearVal As Integer
Dim xlsNewFile As Workbook
monthVal = Month(Date)
dayVal = Day(Date)
yearVal = Year(Date)
Application.CutCopyMode = False
'Indicate here from which sheet you want to copy
ThisWorkbook.Worksheets("Sheet1").Range("A9").Copy
Set xlsNewFile = Workbooks.Add
Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone _
, SkipBlanks:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveWindow.SmallScroll Down:=-12
Application.CutCopyMode = False
If Dir("c:\tmp", vbDirectory) = vbNullString Then
'If Dir("N:\D\IG\C\~ P", vbDirectory) <> vbNullString Then
MsgBox "No such path: N:\D\IG\C\~ P" & Chr(10) & "Skipping first save!"
Else
xlsNewFile.SaveAs Filename:= _
"c:\tmp\" & "-" & yearVal & "." & Format(monthVal, "00") & "." & Format(dayVal, "00") & ".xlsx", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
End If
If Dir("N:\D\IG\C\T\T", vbDirectory) = vbNullString Then
MsgBox "No such path: N:\D\IG\C\T\T" & Chr(10) & "Not saving to second location!"
Else
xlsNewFile.SaveAs Filename:= _
"N:\D\IG\C\T\T" & yearVal & "." & Format(monthVal, "00") & "." & Format(dayVal, "00") & ".xlsx", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
End If
xlsNewFile.Close
End Sub
Let me know if this solved your problems / errors.

Excel VBA Index/Match function not working when indexing another workbook

I have a template that fills certain cells with sales data from another workbook but the other workbook has a new name for each month. When I try to assign a variable as the workbook name so that it finds it each time, I can't get the index/match function to work. Not sure where the error is but is the point where the VBA script fails...
Sub GetNetSales()
Dim Period As String
Dim NS As Workbook
Dim Can As Workbook
Dim BookName As String
Period = Range("Per").Value
Set Can = ThisWorkbook
ChDir "C:\Users\dlibby\Documents\" & Period
Workbooks.Open Filename:= _
"C:\Users\dlibby\Documents\" & Period & "\Net Sales " & Period & ".xlsx"
Set NS = ThisWorkbook
Can.Activate
Range("C10").Select
ActiveCell = _
Application.IfError(Application.Index(NS.Sheets("CM Sales").Columns("E:E"), Application.Match(Can.Range("H10").Value, NS.Sheets("CM Sales").Columns("A:A"), 0)), 0).Value
Range("C10").Select
Selection.Copy
Range("C11:C12").Select
ActiveSheet.Paste
Range("C16:C22").Select
ActiveSheet.Paste
Application.Calculate
Range("C10:C12").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("C16:C22").Select
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
When I am using Index/Match in Macro I am typing formula like this:
Folder = Sheets("Overview").Range("F4")
filename = Sheets("Overview").Range("G4")
filetype = Sheets("Overview").Range("H4")
tabname = Sheets("Overview").Range("I4")
style = Sheets("Overview").Range("J4")
SAPsizecode = Sheets("Overview").Range("K4")
ActiveCell.Formula = "=INDEX('" & Folder & "\[" & filename & filetype & "]" & tabname & "'!$" & SAPsizecode & ":$" & SAPsizecode & ",MATCH(C2,'" & Folder & "\[" & filename & filetype & "]" & tabname & "'!$" & style & ":$" & style & ",0))"
And this works for me. I think the problem in your code is how you are assigning the workbooks. With the approach above you don't need to open another workbook.