简体   繁体   English

Excel VBA打印输出并定义动态打印区域

[英]Excel VBA printout and define dynamic print area

i'm actually trying to, for a command button, set a print area based on colomn A (if A is empty then this row is last row. and when the print area is set, just print it out with landscape layout. My code for now is as follow. When i clic it prints but doesn't update the print area can you help me plz 我实际上是想为命令按钮设置基于列A的打印区域(如果A为空,则此行为最后一行。当设置了打印区域时,只需使用横向布局将其打印出来即可。我的代码现在如下。当我单击时,它可以打印但不更新打印区域,您能帮我吗?

Private Sub Imprimer_Click()

ActiveSheet.Unprotect Password:="mypass"

Dim usedRangeEx As Range
Set usedRangeEx = GetUsedRangeIncludingCharts(ActiveSheet)
usedRangeEx.Activate
Debug.Print usedRangeEx.Address

ActiveSheet.Protect Password:="mypass" 

End Sub

Private Function GetUsedRangeIncludingCharts(target As Worksheet) As Range

ActiveSheet.Unprotect Password:="mypass"

Dim firstRow As Long
Dim firstColumn As Integer
Dim lastRow As Long
Dim lastColumn As Integer
Dim oneChart As ChartObject

    For Each cell In Range("A5:A65")
                If Not IsEmpty(cell) Then
                        lastRow = cell.Row

End If

Next

With target
    firstRow = .UsedRange.cells(1).Row
    firstColumn = .UsedRange.cells(1).Column
    lastColumn = .UsedRange(.UsedRange.cells.Count).Column

Set GetUsedRangeIncludingCharts = .Range(.cells(firstRow, firstColumn), _
                                             .cells(lastRow, lastColumn))
End With

ThisWorkbook.ActiveSheet.PrintOut
With ActiveSheet.PageSetup
    .Zoom = False
    .FitToPagesTall = 1
    .FitToPagesWide = 1

End With

ActiveSheet.Protect Password:="mypass"

End Function

Set your print area 设置您的打印区域

Sub Button1_Click()
    Dim LstRw As Long, PrnG As Range

    LstRw = Cells(Rows.Count, "A").End(xlUp).Row
    Set PrnG = Range("A1:C" & LstRw)    ' or whatever column you want
    ActiveSheet.PageSetup.PrintArea = PrnG.Address

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM