Reputation: 101
I'm making a macro that sets a print area to user selected areas of document. Basically there is a box next to a bunch of cells and if user ticks the box then the bunch of cells is included to the print area. Here is my code so far:
Sub TestCellA1()
Dim t As Integer, d As Integer
t = 0
d = 20
Dim rng_per As Range
Set rng_per = Range("A3:E328") 'prints whole document
Dim rng1 As Range
If Not IsEmpty(Range("F19")) = True Then
ActiveSheet.PageSetup.PrintArea = Range(rng_per)
Else
Do While t < 10
If IsEmpty(Range("F" & d).Value) = True Then
'MsgBox "Do not print"
Else
'MsgBox "Do print"
ActiveSheet.PageSetup.PrintArea = rng1
End If
t = t + 1
d = d + 25
Loop
End If
End Sub
So far this works to the point where the actual work is supposed to be done. I planned that everytime when loop finds box ticked it adds that part of document to the print area. As a newbie with vba I have no idea how to add those areas to print area. Any ideas how to do it? Thanks in advance& have a good day.
Upvotes: 0
Views: 519
Reputation: 12289
If you create and load a range into rng_to_add
, the following will take the existing PrintArea and Union
(append to) the rng_to_add
:
' Going into this, you need to have declared a variable called rng_to_add
Dim rng_to_add As Range
' and loaded the range area you want to add to the PrintArea. This will
' be different for your particular situation.
Set rng_to_add = Sheets("Sheet1").Range("A1:C3")
' Referring to the current PageSetup of the Activesheet..
With ActiveSheet.PageSetup
' Check if the PrintArea of above PageSetup is empty
If .PrintArea = "" Then
' If so, set the PrintArea to the address of the Range: rng_to_add
.PrintArea = rng_to_add.Address
Else
' If not, set it to the address of a union (append) of the existing
' PrintArea's range and the address of the Range: rng_to_add
.PrintArea = Union(Range(.PrintArea), rng_to_add).Address
End If
' End the reference to the current PageSetup of the Activesheet
End With
So, for portability and/or integrating into your existing routines, you could create subroutines that manage the PrintArea like so:
Sub Clear_PrintArea()
' Set PrintArea to nothing
ActiveSheet.PageSetup.PrintArea = ""
End Sub
Sub Add_range_to_PrintArea(rng_to_add As Range)
' Referring to the current PageSetup of the Activesheet..
With ActiveSheet.PageSetup
' Check if the PrintArea of above PageSetup is empty
If .PrintArea = "" Then
' If so, set the PrintArea to the address of the Range: rng_to_add
.PrintArea = rng_to_add.Address
Else
' If not, set it to the address of a union (append) of the existing
' PrintArea's range and the address of the Range: rng_to_add
.PrintArea = Union(Range(.PrintArea), rng_to_add).Address
End If
' End the reference to the current PageSetup of the Activesheet
End With
End Sub
You could then call it like so:
Clear_PrintArea
Add_range_to_PrintArea Range("A1:C3")
Add_range_to_PrintArea Range("A7:C10")
Add_range_to_PrintArea Range("A13:C16")
Upvotes: 2