I convert multiple ranges on different worksheets to a single PDF.
Private Sub CommandButton1_Click()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim vFile As Variant
Dim sFile As String
Set ws1 = Worksheets("Sheet1")
ws1.PageSetup.PrintArea = "B2:K51"
Set ws2 = Worksheets("Sheet2")
ws2.PageSetup.PrintArea = "A3:J52, J3:S52, S3:AE52"
Worksheets(Array(ws1.Name, ws2.Name)).Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=vFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
End If
End Sub
The PrintArea range for ws2 creates a single range.
How do I separate the ranges so the output is three ranges instead of one?
Export to PDF
The solution inserts a new worksheet and copies the ranges to it. Then it exports the new worksheet to PDF and deletes the new worksheet.
Sheet Module e.g. Sheet1 (where the command button is)
Option Explicit
Private Sub CommandButton1_Click()
exportToPDF
End Sub
Standard Module e.g. Module1
Option Explicit
Sub exportToPDF()
' Define constants.
Const Gap As Long = 0
Const vFile As String = "F:\Test\Export.pdf"
Dim Ranges1 As Variant
Ranges1 = Array("B2:K51")
Dim Ranges2 As Variant
Ranges2 = Array("A3:J52", "J3:S52", "S3:AE52")
' Define workbook.
Dim wb As Workbook
Set wb = ThisWorkbook ' The workbook containing this code.
' Define worksheets.
Dim ws1 As Worksheet
Set ws1 = Worksheets("Sheet1")
Dim ws2 As Worksheet
Set ws2 = Worksheets("Sheet2")
Dim ws3 As Worksheet
Set ws3 = wb.Worksheets.Add(After:=wb.Sheets(wb.Sheets.Count))
' Copy ranges from first to third worksheet.
Dim rng As Range
Dim CurrRow As Long
CurrRow = 1
Dim j As Long
Dim RowsCount As Long
Dim ColsCount As Long
For j = LBound(Ranges1) To UBound(Ranges1)
Set rng = ws1.Range(Ranges1(j))
rng.Copy
ws3.Cells(CurrRow, 1).PasteSpecial xlPasteValues
ws3.Cells(CurrRow, 1).PasteSpecial xlFormats
If ColsCount < rng.Columns.Count Then
ColsCount = rng.Columns.Count
End If
CurrRow = CurrRow + rng.Rows.Count + Gap
Next j
' Copy ranges from second to third worksheet.
For j = LBound(Ranges2) To UBound(Ranges2)
Set rng = ws2.Range(Ranges2(j))
rng.Copy
ws3.Cells(CurrRow, 1).PasteSpecial xlPasteValues
ws3.Cells(CurrRow, 1).PasteSpecial xlFormats
If ColsCount < rng.Columns.Count Then
ColsCount = rng.Columns.Count
End If
CurrRow = CurrRow + rng.Rows.Count + Gap
Next j
' Export and close third worksheet.
With ws3
Set rng = .Range("A1").Resize(CurrRow - Gap - 1, ColsCount)
rng.Columns.AutoFit
.PageSetup.PrintArea = rng.Address
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=vFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True
End With
' Inform user.
MsgBox "PDF file has been created."
End Sub
Populate Data (Standard Module)
To quickly see what the code does:
Create a workbook containing worksheets Sheet1 and Sheet2.
Copy all three codes appropriately.
Run populateData.
Run exportPDF.
The Code
Private Sub populateData()
With [Sheet1!B2:K51]
.Formula = "=ROW()&""|""&COLUMN()"
.Interior.ColorIndex = 6
End With
With [Sheet2!A3:AE52]
.Formula = "=ROW()&""|""&COLUMN()"
.Interior.ColorIndex = 8
End With
End Sub
Related
I would Like to only copy the information in Range A2:P13. This Data gets spit out In different rows from time to time, and some times additional data in some of the columns gets added. I wrote a script that allows me to Select and copy everything from the last row to an x number rows up. Problem is that this amount of rows can be variable And there is way more data above the shared image (its clutter). Is there a way to modify my script so it counts down to the last row and once it hits "n" or "Calibration" it selects 8 rows above it?
Thanks in advance :)
enter image description here
Option Explicit
Sub Import_File()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim myValue As Variant
Dim Sht2 As Worksheet
Dim lastRow As Long
Dim Last24Rows As Range
Application.ScreenUpdating = False
Application.DisplayAlerts = False
myValue = InputBox("Please Input Run Number")
FileToOpen = Application.GetOpenFilename("Excel Files (*.xl*),*.xl*", , "Choose File", "Open", False)
If FileToOpen = False Then
Exit Sub
Else
Set OpenBook = Workbooks.Open(FileToOpen)
Set Sht2 = OpenBook.Sheets("Sheet1")
End If
lastRow = Sht2.Range("H" & Sht2.Rows.Count).End(xlUp).row
Set Last4Rows = Sht2.Range("A" & lastRow - 4 & ":AZ" & lastRow)
Last4Rows.Copy
ThisWorkbook.Worksheets(myValue).Range("A1").PasteSpecial xlPasteValues
OpenBook.Close False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I tried Including this
' Dim wb As Workbook
' Dim ws As Worksheet
' Dim FoundCell As Range
' Set wb = ActiveWorkbook
' Set ws = ActiveSheet
'
' Const WHAT_TO_FIND As String = "Calibration"
'
' Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
' If Not FoundCell Is Nothing Then
' MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
' Else
' MsgBox (WHAT_TO_FIND & " not found")
' End If
But it did not work
This will select 8 rows above wherever it finds "calibration". The -8 makes it move up 8 rows, and then the resize(8) resizes it to include the 8 rows below. It will create an error if it can't find "calibration", it would be easy to change that to send a text box instead.
Sub Macro1()
'
' Macro1 Macro
'
'
Dim found As Range
Dim SelectionRange As Range
Dim what_to_find As String
Dim FoundRow As Long
what_to_find = "calibration"
Set found = Cells.Find(What:=what_to_find, After:=ActiveCell, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
FoundRow = found.row
Set SelectionRange = Rows(FoundRow - 8).Resize(8)
SelectionRange.Select
End Sub
I have this macro codes which allow me to copy and paste specific range of one worksheet into a new workbook (both excel and pdf). I need to do the same but for multiple worksheets all at once. How do I modify this code.
Sub SaveData()
' Declare objects
Dim sourceWorkbook As Workbook
Dim targetWorkbook As Workbook
Dim sourceRange As Range
Dim targetRange As Range
Dim cellRange As Range
' Declare other variables
Dim targetWorkbookName As String
Dim targetWorkbookTitle As String
Dim sourceSheetName As String
Dim sourceRangeAddress As String
Dim targetRangeAddress As String
Dim rowCounter As Long
' <<< Customize this >>>
sourceSheetName = "ATP620" ' Name of the source sheet
sourceRangeAddress = "D3:AU197" ' Address of the range you want to copy in the source workbook
targetRangeAddress = "A1" ' Cell address where you want to paste the copied range
targetWorkbookTitle = "ATP620 WP&B 2023" ' Base file name
' Reference source workbook
Set sourceWorkbook = ThisWorkbook
' Create a new workbook
Set targetWorkbook = Application.Workbooks.Add
' Set reference to source range
Set sourceRange = sourceWorkbook.Sheets(sourceSheetName).Range(sourceRangeAddress)
' Copy the range to clipboard
sourceRange.Copy
' This copies the range in the first available worksheet begining in the cell address specified
targetWorkbook.Sheets(1).Range(targetRangeAddress).PasteSpecial Paste:=xlPasteValues
targetWorkbook.Sheets(1).Range(targetRangeAddress).PasteSpecial Paste:=xlPasteFormats
targetWorkbook.Sheets(1).Range(targetRangeAddress).PasteSpecial Paste:=xlPasteColumnWidths
Set targetRange = targetWorkbook.Sheets(1).Range(targetRangeAddress).Resize(sourceRange.Rows.Count, sourceRange.Columns.Count)
' Adjust row heights
For Each cellRange In sourceRange.Columns(1).Cells
rowCounter = rowCounter + 1
targetRange.Rows(rowCounter).RowHeight = cellRange.RowHeight
Next cellRange
' Set the name of the new workbook
targetWorkbookName = Application.GetSaveAsFilename(InitialFileName:=targetWorkbookTitle, _
fileFilter:="Excel Workbooks (*.xlsx),*.xlsx")
' Simultanously export the new workbook into pdf format and set filename the same as the new workbook
sourceRange.ExportAsFixedFormat Type:=xlTypePDF, Filename:=targetWorkbookName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
If targetWorkbookName = vbNullString Then
MsgBox "Saving operation canceled"
Exit Sub
End If
' Save the new workbook
targetWorkbook.SaveAs Filename:=targetWorkbookName ' Un comment this if you want it in OpenXML format: , FileFormat:=xlOpenXMLWorkbook
End Sub
Export a Range
Utilization
Sub ExportDataTEST()
Dim Exceptions() As Variant: Exceptions = Array("Sheet1", "Sheet2")
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet
For Each ws In wb.Worksheets
If IsError(Application.Match(ws.Name, Exceptions, 0)) Then
ExportData ws, "D3:AU197", " WP&B 2023"
End If
Next ws
End Sub
The Method
Sub ExportData( _
ByVal SourceWorksheet As Worksheet, _
ByVal SourceRangeAddress As String, _
ByVal TargetNameSuffix As String)
Const PROC_TITLE As String = "Export Data"
' Reference the Source range.
Dim srg As Range: Set srg = SourceWorksheet.Range(SourceRangeAddress)
' Create and reference a new single-worksheet workbook, the Target workbook.
Dim twb As Workbook: Set twb = Application.Workbooks.Add(xlWBATWorksheet)
' Reference the Target worksheet.
Dim tws As Worksheet: Set tws = twb.Sheets(1) ' the one and only
' Copy/paste.
srg.Copy
With tws.Range("A1")
.PasteSpecial Paste:=xlPasteValues
.PasteSpecial Paste:=xlPasteFormats
.PasteSpecial Paste:=xlPasteColumnWidths
End With
' Adjust the row heights.
Dim sCell As Range, r As Long
For Each sCell In srg.Columns(1).Cells
r = r + 1
tws.Rows(1).RowHeight = sCell.RowHeight
Next sCell
' Get the path of the new workbook.
Dim tBaseName As String: tBaseName = ws.Name & TargetNameSuffix
Dim tPath As Variant: tPath = Application.GetSaveAsFilename( _
InitialFileName:=tBaseName, _
FileFilter:="Excel Workbooks (*.xlsx),*.xlsx")
If VarType(tPath) = vbBoolean Then
MsgBox "Saving operation canceled", vbExclamation, PROC_TITLE
twb.Close SaveChanges:=False
Application.CutCopyMode = False
Exit Sub
End If
' Save the new workbook.
Dim ErrNum As Long
Dim ErrDescription As String
Application.DisplayAlerts = False ' overwrite without confirmation
On Error Resume Next ' e.g. workbook with same name is already open
twb.SaveAs Filename:=tPath
ErrNum = Err.Number
ErrDescription = Err.Description
On Error GoTo 0
Application.DisplayAlerts = True
If ErrNum <> 0 Then
MsgBox "Run-time error '" & ErrNum & vbLf & vbLf & ErrDescription, _
vbCritical, PROC_TITLE
Exit Sub
End If
twb.Close SaveChanges:=False ' just got saved
' Export to PDF.
srg.ExportAsFixedFormat Type:=xlTypePDF, Filename:=tBaseName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
End Sub
I am trying to copy only data from one workbook into a new one, but with only four of the existing worksheets. The code below allows me to successfully copy all worksheets to a new workbook. This worked fine before, but now I only want to copy sheet 2-7, thus excluding sheet 1.
This is done by a user copying data into sheet 1 and the data will be populated to sheets 2-5. Sheet 6 & 7 contains metadata which will be the same for all new workbooks. To be able to import the copied data, I need a new workbook with sheets 2-7.
Sub Button1_Click()
Dim Output As Workbook
Dim Current As String
Dim FileName As String
Set Output = ThisWorkbook
Current = ThisWorkbook.FullName
Application.DisplayAlerts = False
Dim SH As Worksheet
For Each SH In Output.Worksheets
SH.UsedRange.Copy
SH.UsedRange.PasteSpecial xlPasteValuesAndNumberFormats, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False
Next
FileName = ThisWorkbook.Path & "\" & "Generic name.xlsx" 'Change name as needed
Output.SaveAs FileName, XlFileFormat.xlOpenXMLWorkbook
Workbooks.Open Current
Output.Close
Application.DisplayAlerts = True
End Sub
Any suggestions on how improve the code to only copy specified sheets, or to exclude sheet 1?
Copy a Set of Worksheets to Another Workbook
Option Explicit
Sub Button1_Click()
' Constants
Const dFileName As String = "Generic name.xlsx"
Dim DoNotCopy As Variant: DoNotCopy = Array(1) ' add more: Array(1, 7, 8)
Const ConversionWorksheetsCount As Long = 4
' Write the names of the desired worksheets to an array.
Dim swb As Workbook: Set swb = ThisWorkbook
Dim swsCount As Long: swsCount = swb.Worksheets.Count
Dim dwsNames() As String: ReDim dwsNames(1 To swsCount)
Dim sws As Worksheet
Dim sCount As Long
Dim dCount As Long
For Each sws In swb.Worksheets
sCount = sCount + 1
If IsError(Application.Match(sCount, DoNotCopy, 0)) Then
dCount = dCount + 1
dwsNames(dCount) = sws.Name
' Else ' worksheet index found in the 'DoNotCopy' array.
End If
Next sws
If dCount = 0 Then
MsgBox "No worksheets found.", vbCritical
Exit Sub
End If
If dCount < swsCount Then
ReDim Preserve dwsNames(1 To dCount)
End If
Application.ScreenUpdating = False
' Copy the desired worksheets to a new (destination) workbook.
swb.Worksheets(dwsNames).Copy
Dim dwb As Workbook: Set dwb = ActiveWorkbook
' Do the conversions.
Dim dws As Worksheet
Dim n As Long
For n = 1 To ConversionWorksheetsCount
On Error Resume Next
Set dws = dwb.Worksheets(n)
On Error GoTo 0
If Not dws Is Nothing Then ' destination worksheet exists
dws.Activate ' needed for '.Cells(1).Select'
With dws.UsedRange
.Copy
.PasteSpecial xlPasteValuesAndNumberFormats, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False
.Cells(1).Select ' cosmetics
End With
Set dws = Nothing
'Else ' destination worksheet doesn't exist
End If
Next n
'dwb.Worksheets(1).Activate ' cosmetics
' Save the new (destination) workbook.
Dim dFilePath As String: dFilePath = swb.Path & "\" & dFileName
Application.DisplayAlerts = False ' overwrite without confirmation
dwb.SaveAs dFilePath, xlOpenXMLWorkbook
Application.DisplayAlerts = True
dwb.Close
' Note that you never modified the source. It's in the same state as before.
Application.ScreenUpdating = True
MsgBox "Workbook created.", vbInformation
End Sub
Add an If statement after the For Each loop to exclude Sheet1:
For Each SH In Output.Worksheets
If SH.Name <> "Sheet1" Then
SH.UsedRange.Copy
SH.UsedRange.PasteSpecial xlPasteValuesAndNumberFormats, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False
End If
Next
I'm currently working on workbook where in column A:A of worksheet("STAM-Filialen") nearly all the names of the other worksheets are. I want only those worksheets named in column("A:A") in a single PDF. The code I use know makes it a separate file for each worksheet. Is it possible to use a sort of a same code to save it as a single PDF?
Dim myCell As Range
Dim lastCell As Long
Dim PathName As String
lastCell = lastRow("STAM-Filialen")
PathName = Range("I10").Value
Worksheets("STAM-Filialen").Activate
For Each myCell In ThisWorkbook.Worksheets("STAM-Filialen").Range("A2:A" & lastCell).Cells
Dim wksName As String
wksName = myCell.Text
ThisWorkbook.Worksheets(wksName).Range("A1:P60").ExportAsFixedFormat Type:=xlTypePDF, Filename:=PathName & "DispoPlan.Filiaal " & wksName & ".PDF"
Next
I'd recommend moving all the values to a single sheet to print. Then delete this temporary sheet when done.
Here's an example of placing each range from each sheet side by side in a new sheet.
Option Explicit
Public Sub CreateSinglePDF()
Dim ws As Range: Set ws = ThisWorkbook.Sheets(1).Range("A1:A4")
Dim rangeDict As Object: Set rangeDict = CreateObject("Scripting.Dictionary")
Dim cell As Range
For Each cell In ws
If Not rangeDict.exists(cell.Value) And cell.Value <> "" Then
rangeDict.Add cell.Value, ThisWorkbook.Sheets(cell.Value).Range("A1:A5")
End If
Next
Dim printsheet As Worksheet
Set printsheet = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
Dim key As Variant
Dim i As Long: i = 1
For Each key In rangeDict
printsheet.Range(printsheet.Cells(1, i), printsheet.Cells(5, i)).Value = rangeDict(key).Value
i = i + 1
Next
printsheet.UsedRange.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\users\ryan\desktop\ExampleFile.pdf"
printsheet.Delete
End Sub
To convert multiple sheets into single pdf document,
first select multiple sheets
and use the Activesheet.ExportAsFixedFormat statement.
The print range of the page can be set in Page Setup.
Code
Sub test()
Dim WB As Workbook
Dim Ws As Worksheet
Dim sht As Worksheet
Dim PathName As String
Dim vWs() as String '<~~ Variable change
Dim rngDB As Range, rng As Range
Dim n As Integer
Set WB = ThisWorkbook
Set Ws = WB.Worksheets("STAM-Filialen")
PathName = Range("I10").Value
With Ws
Set rngDB = .Range("a1", .Range("a" & Rows.Count).End(xlUp))
End With
For Each rng In rngDB
n = n + 1
ReDim Preserve vWs(1 To n)
vWs(n) = rng.text '<~~ text
Set sht = Sheets(rng.Value)
With sht.PageSetup
.PrintArea = "a1:p60"
End With
Next rng
Sheets(vWs).Select '<~~ multiple sheets select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:=PathName & "DispoPlan.Filiaal.PDF"
End Sub
Worksheets("STAM-Filialen")
Specipic Sheets selected
Single pdf
I have prepared a macro which works fine in demo sheet but gives a 1004 runtime error when it put it in the final sheet.
Below is my code:
Private Sub CommandButton3_Click()
'Declaring the Variables
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim rng As Range
Dim startdate As Long
Dim enddate As Long
Dim tbl As ListObject
Dim fname As Variant
'Assigning the Variables
Set ws = Sheets("Reports")
Set ws3 = Sheets("Report Format")
Set rng = ws.Range("E7")
startdate = ws.Range("L10").Value
enddate = ws.Range("L12").Value
'Find the Worksheet against the Name selected in Drop Down List
For Each ws1 In Worksheets
If rng.Value = ws1.Name Then
Sheets(rng.Value).Activate
End If
Next
'Filter the data based on the Date Range Entered
Set ws2 = ActiveSheet
Set tbl = ws2.ListObjects(1)
Range(tbl & "[[Date]:[Cheque #]]").Select
Selection.AutoFilter Field:=1, Criteria1:=">=" & startdate, Operator:=xlAnd, Criteria2:="<=" & enddate
Selection.Copy
ws2.Range("A10").Select
'Paste the Data in the Report Format
ws3.Activate
ws3.Range("B7").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
'Create the PDF of the Report
fname = Application.GetSaveAsFilename(InitialFileName:=rng.Value, filefilter:="PDF files, *.pdf", Title:="Export to PDF")
If fname <> False Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fname_, quality:=xlQualityStandard, includedocproperties:=True, ignoreprintareas:=False, openafterpublish:=True
End If
'Clear the Report format Sheet for Future Printing
With ActiveSheet
.Rows(10 & ":" & .Rows.Count).Delete
End With
'Activate the Report Sheet
ws.Activate
'Unfilter all the Tables present in Workbook
Dim w As Long
For w = 1 To Worksheets.Count
With Worksheets(w)
**.UsedRange.Cells.EntireRow.Hidden = False**
If .AutoFilterMode Then .ShowAllData
End With
Next w
End Sub
Error appears in line which is highlighted in commas. Kindly review and debug.
You are trying to concatenate a ListObject object into a string. You need the ListObject.Name property.
Dim ws2 As Worksheet, tbl As ListObject
Set ws2 = ActiveSheet
Set tbl = ws2.ListObjects(1)
Debug.Print tbl.Name
Range(tbl.Name & "[[Date]:[Cheque '#]]").Select
Please note that there is also a tick (aka ' or Chr(39)) escaping the hashmark in [Cheque '#].