簡體   English   中英

VBA - 打印多個范圍

[英]VBA - Printing multiple ranges

下面給出了一個在線找到的 VBA 代碼,它有助於從 Excel 打印所需的范圍,但不確定如何改進它以滿足以下條件。 執行時,它會將多個選擇打印到一頁中,但不適合它們。 復制第一個選擇后,第二個進入該頁面的后續行,依此類推。 例如,如果隨機選擇兩個包含 10 個值的列(A 和 C)作為要打印的所需范圍,則第二個選定列 (C) 將位於第一列 (A) 下方。 是否可以修改它以便將第二個(和下一個選擇)定位到第一個選擇/列右側的新列中?

'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

這應該這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM