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

时间:2016-03-30 17:38:39

标签: excel vba excel-vba excel-2010 excel-2007

我实际上试图在命令按钮中设置基于colomn A的打印区域(如果A为空则该行为最后一行。当设置打印区域时,只需将其打印出来横向布局。我现在的代码如下。当我用它来打印但没有更新打印区域时,你可以帮我plz

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

1 个答案:

答案 0 :(得分:2)

设置打印区域

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