【问题标题】:Excel VBA function to only paste what is within the print area rather than the entire sheet?Excel VBA函数仅粘贴打印区域内的内容而不是整个工作表?
【发布时间】:2019-03-28 18:33:28
【问题描述】:

我正在创建一个复制/粘贴 vba 代码,以将我的财务模型转移到单独的 excel 模型中的粘贴版本,并且无法弄清楚如何仅粘贴打印区域中显示的内容。目前它工作得很好,但它会粘贴打印范围之外的所有数据,并显示隐藏在行/列中且未显示的所有数据。

我似乎找不到一个函数或简单函数来添加到已经工作的代码中来执行此操作。我是 VBA 新手,不确定添加此功能的最佳方法。

Sub Test()

    Dim wb As Workbook, wbPaste As Workbook, wsExhibit1 As Worksheet, wsPaste As Worksheet, wsInputs As Worksheet, _
    wsExhibit2 As Worksheet

    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationAutomatic
        .EnableEvents = False
    End With

    Set wb = ThisWorkbook
    Set wbPaste = Workbooks("Copy_PasteWorkbook.xlsx")
    With wb
        Set wsExhibit1 = .Sheets("Value_Summary")
        Set wsInputs = .Sheets("Inputs")
        Set wsExhibit2 = .Sheets("Calculations")
    End With

    With wbPaste
        Set wsPaste = .Sheets.Add(after:=.Sheets(.Sheets.Count))
    End With

    With wsPaste
        wsExhibitA1.UsedRange.Copy
        .Range("A1").PasteSpecial xlPasteValues
        .Range("A1").PasteSpecial xlPasteFormats
        .Range("A1").PasteSpecial xlPasteColumnWidths
        .Name = .Cells(1, 3)
    End With

    wsInputs.Range("Selected_Calculation").Value = 1
    Do Until wsInputs.Range("Selected_Calculation").Value > wsInputs.Range("Total_Calculations").Value
        Application.Calculate
        With wbPaste
            Set wsTemp = .Sheets.Add(after:=.Sheets(.Sheets.Count))
        End With
        With wsTemp
            wsExhibit2.UsedRange.Copy
            .Range("A1").PasteSpecial xlPasteValues
            .Range("A1").PasteSpecial xlPasteFormats
            .Range("A1").PasteSpecial xlPasteColumnWidths
            .Name = .Cells(1, 3)
        End With
    wsInputs.Range("Selected_Calculation").Value = wsInputs.Range("Selected_Calculation").Value + 1
    DoEvents
    Loop
    wsInputs.Range("Selected_Calculation").Value = 1

    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationAutomatic
        .EnableEvents = False
        .CutCopyMode = False
    End With

End Sub

我希望仅将工作簿中设置的打印区域内的内容粘贴到相应页面上。不粘贴隐藏数据或超出范围的数据。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    Print_Area 是一个命名范围。

    Sheets(“SheetName”).Range(“Print_Area”).Copy
    

    为了避免隐藏单元格:

    Sheets(“SheetName”).Range(“Print_Area”).SpecialCells(xlCellTypeVisible).Copy
    

    【讨论】:

    • 当然,答案很简单。感谢您的帮助。关于如何忽略粘贴中隐藏的行/列的任何提示?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2016-02-28
    • 1970-01-01
    相关资源
    最近更新 更多