I need help here. I have Sheet 1 and Sheet2. and in Sheet1/2 I have dates in the column B and both sheet dates are not same but when I commend for Select date for print I want VBA to select nearest date if it coudn't find my date. For example:- if I ask VBA to print from date 12-Aug-17 I can be selected in sheet1 but in Sheet 2 there is no 12th Aug so it has to select 13th or 11th and print. In my coding, if it’s in same date it will print both the sheet. But if it fails then it will show the error.
Code
Sub CreatePDF()
Dim Sh As Worksheet
Set sh2 = Sheets("Sheet2")
Set sh3 = Sheets("Sheet3")
Dim i, j2, j3, sh2EndCell, sh3EndCell As Integer
Dim closest As Date
Dim W1Enddate As Date
W1Enddate = Application.InputBox("Enter the End Date")
sh2EndCell = sh2.Range("b" & Rows.Count).End(xlUp).Row
sh3EndCell = sh3.Range("b" & Rows.Count).End(xlUp).Row
For i = 2 To sh2EndCell
If sh2.Range("b" & i).Value = W1Enddate Then
j2 = i
Exit For
End If
Next i
For i = 2 To sh3EndCell
If sh3.Range("b" & i).Value = W1Enddate Then
j3 = i
Exit For
End If
Next i
sh2.Range("A1", "K" & j2).PrintPreview
sh3.Range("A1", "K" & j3).PrintPreview
Application.ScreenUpdating = False
sh2.PageSetup.PrintArea = ("A1:K" & j2)
sh3.PageSetup.PrintArea = ("A1:K" & j3)
Sheets(Array("sheet2", "sheet3")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="", _
OpenAfterPublish:=True
Application.ScreenUpdating = True
End Sub
Please see Above my code.