简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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