Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Hide empty rows before TOTAL row when save file as PDF

0

Hello

this  code  works  very  well, but  I  need  when save  the  file as  PDF   shouldn't  show empty  rows based range B:F 

the  column A always filled numbers 1,2... and  column G  is  filled formula  . so  I  want  dealing for  columns B21:F  if  this  range  is  empty .

I  have  two  challenges :

1- I  have  word  TOTAL in lastrow  for  column A   and  columns B:F in TOTAL row  will be  empty ,then  I'm afraid  will  delete TOTAL row  if  I  depend on B: F to hide rows .

2-  will add new rows  before TOTAL  row  so  I  can't  specify  specific range 

last  thing  when  hide  row should  just  show  when  save  the  file as PDF   but  the  excel file  should  keep as  in orginal data  without  hid  any  rows  after save  the file .

Public Sub Save_Columns_As_PDF()

    Dim mainFolder As String, subfolder As String, PDFfile As String
    Dim lastRow As Long

    mainFolder = "C:\Users\pc\Desktop\ARCHIVE\"

    If Right(mainFolder, 1) <> "\" Then mainFolder = mainFolder & "\"

    With ActiveWorkbook.Sheets("SH1")
        subfolder = mainFolder & .Range("G1").Value & "\"
        If Dir(subfolder, vbDirectory) = vbNullString Then MkDir subfolder
        subfolder = subfolder & UCase(Format(Date, "mmm")) & "\"
        If Dir(subfolder, vbDirectory) = vbNullString Then MkDir subfolder
        PDFfile = subfolder & .Range("G6").Value & ".pdf"
        lastRow = .Range("A:G").Find("*", , , , xlByRows, xlPrevious).Row
        .Range("A1:G" & lastRow).ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDFfile, _
            Quality:=xlQualityMinimum, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
    End With

    MsgBox "Created " & PDFfile, vbInformation

End Sub

thanks in advance .

Answer
Discuss

Answers

0
Selected Answer

Hi Kalil

Not sure I understand your question fully (and you didn't upload a file) but the attached file includes the revised code below.

If you click the peach coloured button "Create pdf (without blank rows)", it will create a pdf of the data but skip any rows which are all blank.

Revision 17 June 2023 (to find blank cells in B:F only)

It hides those by checking if the number of blanks cells is the same as the number of cells in the row of the range B:F. Once the pdf is printed, all rows are unhidden.

Second revision 17 June 2023 (using user file and keeping rows 1 to 20)

The code now clears blank rows between row 20 and the last (TOTAL) row a file and the users file sheets are used.

Changes are in bold including a better way to determine the last used row (of column A):

Public Sub Save_Columns_As_PDF()

    Dim mainFolder As String, subfolder As String, PDFfile As String
    Dim lastRow As Long
    Dim n As Long

    mainFolder = "C:\Users\pc\Desktop\ARCHIVE\"
    If Right(mainFolder, 1) <> "\" Then mainFolder = mainFolder & "\"

    With ActiveWorkbook.Sheets("INVOICE")
        subfolder = mainFolder & .Range("G1").Value & "\"
        If Dir(subfolder, vbDirectory) = vbNullString Then MkDir subfolder
        subfolder = subfolder & UCase(Format(Date, "mmm")) & "\"
        If Dir(subfolder, vbDirectory) = vbNullString Then MkDir subfolder
        PDFfile = subfolder & .Range("G6").Value & ".pdf"

        ' get last used row in column A
        lastRow = .Range("A" & Rows.Count).End(xlUp).Row
        ' don't show user when rows are hidden
        Application.ScreenUpdating = False

        ' loop down rowsfrom row 21 to before total
        For n = 21 To lastRow - 1
            ' look in B:F
            Set ChkRow = Intersect(.Rows(n), .Range("B1:F" & lastRow))
            ' hide row if all are blank cells
            If WorksheetFunction.CountBlank(ChkRow) = ChkRow.Cells.Count Then
                .Rows(n).Hidden = True
            End If
        Next n
        ' print non-blank range
        With .Range("A1:G" & lastRow)
            .ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDFfile, _
            Quality:=xlQualityMinimum, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
            'unhide blank rows
            .EntireRow.Hidden = False
        End With

        Application.ScreenUpdating = True
    End With

    MsgBox "Created " & PDFfile, vbInformation

End Sub

The user will just see the message that the file has been created.

Note that your choice of white font on a yellow background is low contrast and may be difficult to read for some people. I'd suggest you change the font to black or make the cell background a darker colour.

Other users should note that cells G1 and G6 are used to create the folder path and file name respectively.

Hope this is what you need. If so, please remember to mark this Answer as Selected.

Discuss

Discussion

Hi John,
based on  your  file you  stiil don't  understand  me . not  the  whole  range  is  empty . look at  the  row 16,17   before TOTAL row  in  my  case like  this  ROWS 16,17
A           B          C          D         E         F      G 
1                                                                   0.00
2                                                                   0.00
should  search  for the  empty range(B:F), if  range(B:F)  is  empty  then  should  hide rows 16,17 when save  file  . the  column G  is  the  formula.  should  just  search before TOTAL row  and  after   row 15    I  consider the  row 15  is  headers  in this  case should just hide rows  16,17  and  ignore headers in row a15 and ignore TOTAL row . the header in row15  is   fixed but TOTAL row  will be  changed  because  I  add rows before it  every time
Kalil (rep: 36) Jun 17, '23 at 10:03 am
Kalil

Please see my revised Answer and file.

To check in B:F only, I just chnaged the bit in bold in the code extract below:
        ' loop down rows
        For n = 1 To lastRow
            ' look in B:F
            Set ChkRow = Intersect(.Rows(n), .Range("B1:F" & lastRow))
John_Ru (rep: 6142) Jun 17, '23 at 10:44 am
Sorry- just had to replace the revised file (so the button worked again)
John_Ru (rep: 6142) Jun 17, '23 at 10:47 am
sorry  John  this  is  not  I  want  it .
as  I  said ,   just   start  after  row 20 and  before  TOTAL  row .
so  I attached  the  file , see the  second sheet  how  should  be 
again just  deal  after  headers and  before TOTAL row .
Kalil (rep: 36) Jun 17, '23 at 3:23 pm
Kalil

Please see Second revision 17 June 2023 and a revised code/ file. I haven't the time to explain what minor changes were made but you should be able to work it out.

It save us time since - if your question wording isn't quite right- we should be able to create a solution without several revisions,
John_Ru (rep: 6142) Jun 17, '23 at 4:18 pm
sorry about not  attaching  file  from the beginning !
I  don't  think  the  things  will be  complicated  and  unclear  with  my  details .
finally  works perfectly 
many  thanks  for  your  time ,John 
Kalil (rep: 36) Jun 17, '23 at 4:31 pm
Glad that worked (finally). It really helps to see a file first- Willie and I would have got to a solution earlier I'm pretty sure (and we don't like re-working things if that can be avoided!). Thanks for selecting my Answer Kalil.
John_Ru (rep: 6142) Jun 17, '23 at 4:36 pm
Add to Discussion
0

Hello Kalil,

I took a similar approach as John did except my code assumes that all cells B:F, below the last row in "B" with data, are empty. Also, at the end of the code it enters a new row above the TOTAL row (point #2 in your original post)

Public Sub Save_Columns_As_PDF()

' macro modified by Willied24 for teachexcel.com

    Dim mainFolder As String, subfolder As String, PDFfile As String
    ' Dim lastRow As Long
'========================================
' new
Dim LR_A As Long   ' last blank/empty row in "A"
Dim LR_B As Long   ' last blank/empty row in "B"

LR_A = (Cells(Rows.Count, 1).End(xlUp).Row) - 1
LR_B = (Cells(Rows.Count, 2).End(xlUp).Row) + 1
'========================================

mainFolder = "C:\Users\pc\Desktop\ARCHIVE\"

' not required because line above includes ending "\"
'If Right(mainFolder, 1) <> "\" Then mainFolder = mainFolder & "\"

Application.ScreenUpdating = False

    With ActiveWorkbook.Sheets("SH1")
        subfolder = mainFolder & .Range("G1").Value & "\"
        If Dir(subfolder, vbDirectory) = vbNullString Then MkDir subfolder
        subfolder = subfolder & UCase(Format(Date, "mmm")) & "\"
        If Dir(subfolder, vbDirectory) = vbNullString Then MkDir subfolder
        PDFfile = subfolder & .Range("G6").Value & ".pdf"

'========================================
 ' hide the blank rows
Worksheets("SH1").Range("LR_B:LR_A").EntireRow.Hidden = True
'========================================

' new version
.Range("A1:G" & LR_A).ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDFfile, _
            Quality:=xlQualityMinimum, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False

' un-hide the hidden rows
Worksheets("SH1").Range("LR_B:LR_A").EntireRow.Hidden = False
'========================================
' insert new row above "TOTAL" row
Rows(LR_A + 1).Insert , xlFormatFromLeftOrAbove
'========================================
Application.ScreenUpdating = True
    End With

    MsgBox "Created " & PDFfile, vbInformation

End Sub

If you prefer this method, please mark the answer as seleted.

Cheers   :-)

Discuss

Discussion

Hi Willie !
gives mismatch in this line 
Rows("LB_B:LR_A").EntireRow.Hidden = True
Kalil (rep: 36) Jun 17, '23 at 10:05 am
I hadn't tested the code, the error is due to a small syntax error. the line should read:
Worksheets("SH1").Range("LR_B:LR_A").EntireRow.Hidden = True

In the above macro I have corrected it for both the "hide" and "un-hide".
WillieD24 (rep: 557) Jun 18, '23 at 8:49 am
application defined  error  in  the same  line .
Kalil (rep: 36) Jun 18, '23 at 1:38 pm
@Willie Did you test your last suggestion above? It includes LB_B but your variable is LR_B (hence the initial application error). Furthermore you have two Long variables, determined as: 
LR_A = (Cells(Rows.Count, 1).End(xlUp).Row) - 1
LR_B = (Cells(Rows.Count, 2).End(xlUp).Row) + 1
so two numbers, say 22 and 25. Your intended expression .Range("LR_B:LR_A")  won't evaluate to a range of cells and even Range(LR_B & ":" & LR_A) wouldn't make sense to VBA. I haven't worked through the logic of your code but this expression would hide rows:
 ' hide the blank rows
Worksheets("SH1").Rows(LR_B & ":" & LR_A).EntireRow.Hidden = True

@Kalil If you prefer Willie's solution (once it's working) to mine, you'll need to deselect mine then Select this one (since there can only be one Selected Answer per question).
John_Ru (rep: 6142) Jun 19, '23 at 5:14 am
@John even  if  I    correct  based  on declared  variable  still  shows the  same  error  in  the  same line .
Kalil (rep: 36) Jun 19, '23 at 3:53 pm
@Kalil that's odd (unless  LR-A is less than LR_B) but I'll leave it to Willie to sort his code out. In the meantime. hope my solution is still working well. 
John_Ru (rep: 6142) Jun 19, '23 at 5:21 pm
@John:
Thanks for catching my error. I have corrected all of the LB errors to LR as they should be. I was tired and when reviewing it LB looked like LR. (LOL)
I have downloaded Kalil's file and I see now that my method won't work (I made it before a sample file was uploaded. The TOTAL row is 22. There is data in A20 & A21 and B20 & B21 so I see now my method and code won't work with Kalil's table structure.

Cheers   :-)
WillieD24 (rep: 557) Jun 20, '23 at 2:43 am
@Willie- that's understandable, it happens. I didn't check your file but thought Rows() was needed. 

@Kalil- you have a working solution so I think Willie won't spend more time refining his approach. 
John_Ru (rep: 6142) Jun 20, '23 at 2:54 am
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login