Home > Blockchain >  VBA - Printing multiple ranges
VBA - Printing multiple ranges

Time:11-27

Below is given a VBA code found online which is helpful to print desired ranges from an Excel but not sure how to improve it in order to fulfil the following condition. When executed, it prints out multiple selections into one page but does not properly fit them. After copying the first selection, the second one comes in subsequential row of that page and so on. For instance, if two random columns (A and C) containing 10 values each are selected as desired ranges to be printed out, the second selected column (C) will fit below the first column (A). Is it possible to modify it so that the second (and next selections) will be positioned into a new column on the right side of the first selection/column?

'VBA Code
Sub printOutRange()
Dim xRng1 As Range
Dim xRng2 As Range
Dim xNewWs As Worksheet
Dim xWs As Worksheet
Dim xIndex As Long
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set xWs = ActiveSheet
Set xNewWs = Worksheets.Add
xWs.Select
xIndex = 1
For Each xRng2 In Selection.Areas
    xRng2.Copy
    Set xRng1 = xNewWs.Cells(xIndex, 1)
    xRng1.PasteSpecial xlPasteValues
    xRng1.PasteSpecial xlPasteFormats
    xIndex = xIndex   xRng2.Rows.Count
Next
xNewWs.Columns.AutoFit
xNewWs.PrintPreview
xNewWs.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

CodePudding user response:

This should do it:

Dim xRng1 As Range
Dim xRng2 As Range
Dim xNewWs As Worksheet
Dim xWs As Worksheet
Dim xIndex As Long
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set xWs = ActiveSheet
Set xNewWs = Worksheets.Add
xWs.Select
xIndex = 1
For Each xRng2 In Selection.Areas
    xRng2.Copy
    Set xRng1 = xNewWs.Cells(1, xIndex)
    xRng1.PasteSpecial xlPasteValues
    xRng1.PasteSpecial xlPasteFormats
    xIndex = xIndex   1
Next
xNewWs.Columns.AutoFit
xNewWs.PrintPreview
xNewWs.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
  • Related