简体   繁体   中英

Excel Macro - Dynamically Set Print Area

I have a table with a fixed number of columns, but the number of rows vary week on week.

Is there a macro I can create to set the print area automatically of this table?

I would combine a dynamically resizing named range with a VBA method.

First create a named range, MyNamedRange: (Assuming your table begins at $A$1 and your table has headers)

=OFFSET(A1,0,0,COUNTA(A:A)-1,COUNTA(1:1))

Then just execute a line of VBA:

ActiveSheet.PageSetup.PrintArea = "MyNamedRange"

Just use this simple code:

 Private Sub prnt()
 On Error Resume Next

  Cells(1, 1).Select
  With ActiveSheet.PageSetup
    .PrintArea = Range(ActiveCell, ActiveCell.SpecialCells(xlCellTypeLastCell)).Select.Address
    .Orientation = xlLandscape
    .LeftHeader = "&p/&N"
    .LeftFooter = ActiveWorkbook.FullName 'to show address
    .PrintTitleRows = "$1:$5" 'repeat at top
    .Zoom = False
    .Orientation = xlLandscape
    .FitToPagesWide = 1 'to print in 01 page
    .FitToPagesTall = False 'to print in 01 page
  End With
End Sub

I guess this is a pretty late response... The solution above didn't work for me in Excel 2007 so I used

begin_column = 1
end_column = 5

begin_row = 1
end_row = 30

'converting the numbers to uppercase letters
temp_begin_column = Chr(first_column + 64)
temp_end_column = Chr(second_column + 64)

ActiveSheet.PageSetup.PrintArea = "$" & temp_begin_column & "$" & begin_row & ":$" & temp_end_column & "$" & end_row

This may seem like a complicated solution but its the only thing that reliably worked for me

I have tried this and it Worked for me.

StartColumn="A"
StartRow=1
EndColumn="B"
EndRow=10

ActiveSheet.PageSetup.PrintArea = StartColumn & StartRow & ":" & EndColumn & EndRow
ActiveSheet.PageSetup.PrintArea = "A1:B10"

Or 
ActiveSheet.PageSetup.PrintArea = "$" & StartColumn & "$" & StartRow & ":" & "$"  & EndColumn & "$" & EndRow
ActiveSheet.PageSetup.PrintArea = "$A$1:$B$10"

If you're wanting to print the whole sheet always, you can actually just clear the print area and it will default to the amount of the sheet that is filled with data. If you're wanting not to hide some columns, wtfsven's answer is perfect.

ActiveSheet.PageSetup.PrintArea = "MyNamedRange" as proposed above by Stephen Collins does not work for me.

But if I typed a slightly modified version: ActiveSheet.PageSetup.PrintArea = MyNamedRange.Address then it works perfectly in my context.

I had Application.ReferenceStyle = xlR1C1 activated and not xlA1.

Note: ActiveSheet.PageSetup.PrintArea = MyNamedRange.Address(ReferenceStyle:=xlR1C1) would not work for me.

Similarly, ActiveSheet.PageSetup.PrintArea = StartColumn & StartRow & ":" & EndColumn & EndRow as proposed above by Bhanu Pratap works indeed very well, 1st time. Bu not so easy to manage programmatically (column letters).

But using "R" & StartRow & "C" & StartColumn & ":" & "R" & EndRow & "C" & EndColumn --- does not work for me either. So, consistent.

Looking at https://docs.microsoft.com/en-us/office/vba/api/excel.pagesetup.printarea it states that " you use the Address property to return an A1-style address. "

So, it seems to be an expected VBA behaviour not to use xlR1C1 while it would be much easier to use programmatically.

My simple way around it:

Set MyNamedRange = Worksheets(i_sheet_idx).Range(Cells(StartRow, StartColumn), Cells(EndRow, EndColumn)) -- using the same variables as suggested above by Bhanu Pratap.

Then ActiveSheet.PageSetup.PrintArea = MyNameRange.Address ' which does the job for me.

So, I can programmatically play with the start/End Row/Columns easily. Using offset as suggested above should work also to change the range but this is independent from the programmatic difficulty encountered here in VBA to specify the range address in a way VBA would accept to swallow without error. I would not want to count the strange & unclear VBA errors I had on these trials. I don't use VBA often & never program otherwise (hence the struggle above). The goal was to print automatically, smartly & recurrently a large number of parts of a large worksheet following a pattern.

NB: possibly unrelated, I encountered in the debugging phase - just on the PageSetup.PrintArea line - as above a strange phenomenon where even if no error (so the code following later after rerun a fully expected & controlled path), my code would jump - sometimes - to a totally different sub or function in another workbook without reason (I have another personal workbook storing a number of work macros in several modules). It happens 4 times in tests. I tried to find events that could trigger this but could not find one. Sometimes it was the same sub/function being triggered, sometimes it was a different one, with no logical connection. But I noted that I had seen the same function being triggered in another situation before (see its basic code below), without good reason. So, something must happen at application level. In this "short piece of code" just written to test the above, I introduced later an error handler to catch err.number in case a problem would occur but of course, it did not reoccur.

I suppose that closing & restarting Excel (2013 here) should fix this error. This has happened to me before once in Excel 2010. A pointer going nuts but with some insistence, a repeated folly which supposes some logic behind. Weird.
Here is the function most often triggered in another module in another workbook (while not being programmatically activated at all, I repeat): it does not make logical sense to me but so it is:

Function HLink(rng As Range) As String 'extract URL from hyperlink If rng(1).Hyperlinks.Count Then HLink = rng.Hyperlinks(1).Address End Function

The other sub being activated did not make more apparent sense.

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