Search code examples
excelbuttonprintingconditional-statementsworksheet

Creating a print button based on conditional criteria in Excel


So first my disclaimer. While I have some programming background, im not proficient in VB scripting so I may need some hand holding on this but I am mighty grateful for any help you wonderful people can render.

Im creating a print button that will print a worksheet based on criteria that the user will type in. Well basically I need the script to check certain cells in a row and if there is data in those cells, move to the next line. Rinse and repeat until you get to a row with no data in those certain cells and then automatically print the correct number of pages based on the data. I hope that makes sense. I hope that makes sense.


Solution

  • I tried writing a piece of code to check certain columns and return the value when all of those columns are blank. Hope that helps you

       Sub Printing()
            Dim CheckCol1 As Integer, CheckCol2 As Integer
            Dim rowCount As Integer, rowCount1 As Integer, rowCount2 As Integer, currentRow As Integer
            Dim currentRowValue1 As String, currentRowValue2 As String
            Dim found As String
            found = "No"
            CheckCol1 = 1   'column A has a value of 1
            CheckCol2 = 2   'column B has a value of 2
    
            rowCount1 = Cells(Rows.Count, CheckCol1).End(xlUp).Row
            rowCount2 = Cells(Rows.Count, CheckCol2).End(xlUp).Row
            rowCount = Application.Max(rowCount1, rowCount2)
    
            ' find the first blank cell on both the columns
            For currentRow = 1 To rowCount
                currentRowValue1 = Cells(currentRow, CheckCol1).Value
                currentRowValue2 = Cells(currentRow, CheckCol2).Value
    
                If (IsEmpty(currentRowValue1) Or currentRowValue1 = "") And (IsEmpty(currentRowValue2) Or currentRowValue2 = "") Then
                  MsgBox ("No data on Column A and B in row" & currentRow)
                  found = "Yes"
                End If
            Next
            If found = "No" Then ' This will return rowcount+1 when the columns have values throughout the range 
               MsgBox ("No data on Column A and B in row" & rowCount + 1)
             End If
    
        End Sub
    

    Note:- You can increase the number of columns to be checked by adding few variables. You can try Adding third column by adding Checkcol3, rowcount3, currentrowvalue3 and adding one more condition to the if clause