Save to PDF loop not working - vba

Solved.
The macro loops through a table and autofills values into the destination sheet and automatically saves as a pdf on the desktop with a specified file name for each row. It does not save them into a single pdf; however, if you have adobe acrobat it has a simple merge tool to combine them together.
Sub AutoFill_export2pdf()
'
Dim rowCount As Integer
Dim CurBU As String
Dim CurOPRID As String
Dim CurName As String
Dim CurJournalID As String
Dim CurJournalDate As String
Dim FILE_NAME As String
Sheets("List").Select
rowCount = ActiveSheet.UsedRange.Rows.count
Set Destsh = ActiveWorkbook.Sheets("Sheet")
For sourceRow = 2 To rowCount
CurOPRID = Range("A" & CStr(sourceRow)) 'OPRID
CurName = Range("B" & CStr(sourceRow)) 'Name
CurBU = Range("C" & CStr(sourceRow)) 'BU
CurJournalID = Range("D" & CStr(sourceRow)) 'Journal ID
CurJournalDate = Range("E" & CStr(sourceRow)) 'Journal Date
FILE_NAME = ActiveWorkbook.Path & "\" & "OTGL_" & "JRNL_" & CurBU & "_" & CurJournalID & "_" & Format(CurJournalDate, "mm-dd-yyyy") & "_" & ".PDF"
CurName = "*" & CurName & "*"
CurBU = "*" & CurBU & "*"
CurJournalID = "*" & CurJournalID & "*"
CurJournalDate = "*" & CurJournalDate & "*"
Destsh.Range("K27") = CurName
Destsh.Range("D7") = CurBU
Destsh.Range("G7") = CurJournalID
Destsh.Range("I7") = CurJournalDate
On Error GoTo 0
Call SaveAsPDF(Destsh, FILE_NAME)
Sheets("List").Select
Next
End Sub
Public Sub SaveAsPDF(ByVal destSheet As Worksheet, ByVal PDFName As String)
On Error Resume Next
Kill PDFName
destSheet.Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
PDFName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End Sub
Sub Autofill()
'
Dim rowCount As Integer
Dim CurBU As String
Dim CurName As String
Dim CurOPRID As String
Dim CurJournalID As String
Dim CurJournalDate As String
Dim FILE_NAME As String
CurName = "*" & CurName & "*"
CurBU = "*" & CurBU & "*"
CurJournalID = "*" & CurJournalID & "*"
CurJournalDate = "*" & CurJournalDate & "*"
Sheets("List").Select
rowCount = ActiveSheet.UsedRange.Rows.count
Set Destsh = ActiveWorkbook.Sheets("Sheet")
For sourceRow = 2 To rowCount
CurOPRID = Range("A" & CStr(sourceRow)) 'OPRID
CurName = Range("B" & CStr(sourceRow)) 'Name
CurBU = Range("C" & CStr(sourceRow)) 'BU
CurJournalID = Range("D" & CStr(sourceRow)) 'Journal ID
CurJournalDate = Range("E" & CStr(sourceRow)) 'Journal Date
FILE_NAME = ActiveWorkbook.Path & "\" & "OTGL_" & "JRNL_" & CurBU & "_" & CurJournalID & "_" & Format(CurJournalDate, "mm-dd-yyyy") & "_" & ".PDF"
Destsh.Range("K27") = CurName
Destsh.Range("D7") = CurBU
Destsh.Range("G7") = CurJournalID
Destsh.Range("I7") = CurJournalDate
On Error GoTo 0
Call SaveAsPDF(Destsh, FILE_NAME)
Sheets("List").Select
Next
End Sub
End Sub

You want to export just the Destination sheet (Destsh). So use
Destsh.ExportAsFixedFormat Type:=xlTypePDF, _
filename:="fp", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Instead of
wb.ExportAsFixedFormat Type:=xlTypePDF, _
filename:="fp", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Also this will just save the file to "fp" you want to use something like
filename:= fp & "\mysheetname.pdf"

Related

VBA code to combine powerquery tables into one new table

Ok, here's my issue, I managed to dynamicly load new tables into the powerquery datamodel.
I would like to combine all these tables into one new one called Allcontrols.
My approach is to try a for each loop and add every new table seperatly.
So far I am getting an error in m om the code in the combine tables section. Help is much appreciated.
Sub Add_Connection_All_Tables()
'Creates Connection Only Queries to all tables in the active workbook.
Dim wb As Workbook
Dim ws As Worksheet
Dim lo As ListObject
Dim sName As String
Dim sFormula As String
Dim wq As WorkbookQuery
Dim bExists As Boolean
Dim vbAnswer As VbMsgBoxResult
Dim vbDataModel As VbMsgBoxResult
Dim i As Long
Dim dStart As Double
Dim dTime As Double
Dim cn As WorkbookConnection
Unprotectwb
UnprotectSh
'Set variables
Set wb = ActiveWorkbook
'Clear connections
On Error Resume Next
For Each cn In ThisWorkbook.Connections
cn.Delete
Next
'Clear queries
For Each wq In wb.Queries
wq.Delete
Next wq
'Loop sheets and tables
For Each ws In ActiveWorkbook.Worksheets
For Each lo In ws.ListObjects
sName = lo.Name
If Left(sName, 3) Like "WP_" Then
sFormula = "Excel.CurrentWorkbook(){[Name=""" & sName & """]}[Content]"
'Check if query exists
bExists = False
For Each wq In wb.Queries
If InStr(1, wq.Formula, sFormula) > 0 Then
bExists = True
End If
Next wq
'Add query if it does not exist
If bExists = False Then
'Add query
wb.Queries.Add Name:=sName, _
Formula:="let" & Chr(13) & "" & Chr(10) & " Source = Excel.CurrentWorkbook(){[Name=""" & sName & """]}[Content]" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source"
'Add connection
wb.Connections.Add2 Name:="Query - " & sName, _
Description:="Connection to the '" & sName & "' query in the workbook.", _
ConnectionString:="OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & sName & ";Extended Properties=""""", _
CommandText:="SELECT * FROM [" & sName & "]", _
lCmdtype:=2, _
CreateModelConnection:=False, _
ImportRelationships:=False
'Add to datamodel
wb.Connections.Add2 Name:="Query - " & sName, _
Description:="Connection to the '" & sName & "' query in the workbook.", _
ConnectionString:="OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & sName & ";Extended Properties=", _
CommandText:="" & sName & "", _
lCmdtype:=6, _
CreateModelConnection:=True, _
ImportRelationships:=False
'Combine tables section
ActiveWorkbook.Queries.Add Name:="Allcontrols", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Table.Combine({""" & sName & """})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source"
End If
End If
Next lo
Next ws
'Protectwb
'ProtectSh
End Sub

Extract a column range from excel worksheets

I am currently working on parsing data from multiple worksheets within multiple workbooks into a summary worksheet. I have been able to select certain cells from all sheets and workbooks but would like to extract a range of columns if possible. How can I add this option to my loop condition?
for example If I have a worksheet called "Monday" and I would like to extract the cell range A2 through C57 and add it to my newly created worksheet.
Option Explicit
Sub GetMyData()
Dim myDir As String, fn As String, SheetName As String, SheetName2 As String, SheetName3 As String, n As Long, NR As Long
'***** Change Folder Path *****
myDir = "C:\attach"
'***** Change Sheetname(s) *****
SheetName = "Title"
SheetName2 = "Total"
SheetName3 = "Monday"
'***Loops through specified directory and parces data from each worksheet within each workbook by selecting specified .
fn = Dir(myDir & "\*.xlsx")
Do While fn <> ""
If fn <> ThisWorkbook.Name Then
With ThisWorkbook.Sheets("ImportTable")
NR = .Cells(Rows.Count, 1).End(xlUp).Row + 1
'Pick cells from worksheet "Title"
With .Range("A" & NR)
.Formula = "='" & myDir & "\[" & fn & "]" & SheetName & "'!A1"
.Value = .Value
End With
With .Range("B" & NR)
.Formula = "='" & myDir & "\[" & fn & "]" & SheetName & "'!A2"
.Value = .Value
End With
With .Range("C" & NR)
.Formula = "='" & myDir & "\[" & fn & "]" & SheetName & "'!B4"
.Value = .Value
End With
With .Range("D" & NR)
.Formula = "='" & myDir & "\[" & fn & "]" & SheetName & "'!B5"
.Value = .Value
End With
With .Range("E" & NR)
.Formula = "='" & myDir & "\[" & fn & "]" & SheetName & "'!B6"
.Value = .Value
End With
With .Range("F" & NR)
.Formula = "='" & myDir & "\[" & fn & "]" & SheetName & "'!B7"
.Value = .Value
End With
With .Range("G" & NR)
.Formula = "='" & myDir & "\[" & fn & "]" & SheetName2 & "'!B26"
.Value = .Value
End With
With .Range("H" & NR)
.Formula = "='" & myDir & "\[" & fn & "]" & SheetName2 & "'!A1"
.Value = .Value
End With
End With
End If
fn = Dir
Loop
ThisWorkbook.Sheets("ImportTable").Columns.AutoFit
End Sub
If you move your link creation to a separate sub your code will be more concise, and you can have the sub automatically adjust the type of formula (regular for single cells, or array formula for blocks of cells)
Sub tester()
Dim rng As Range
Set rng = ActiveSheet.Range("A2")
LinkToFile "C:\_Stuff\test", "temp report.xlsx", "Sheet1", "A1:D20", rng
Set rng = ActiveSheet.Range("F2")
LinkToFile "C:\_Stuff\test", "temp report.xlsx", "Sheet1", "A1", rng
End Sub
Sub LinkToFile(fPath As String, fName As String, shtName As String, _
addr As String, rngInsert As Range)
Dim rngTmp As Range, f As String
If Right(fPath, 1) <> "\" Then fPath = fPath & "\" 'win only!
f = "='" & fPath & "[" & fName & "]" & shtName & "'!" & addr
'linking to a range, or a single cell ?
If InStr(addr, ":") > 0 Then
Set rngTmp = rngInsert.Parent.Range(addr) 'to get num rows/cols
rngInsert.Resize(rngTmp.Rows.Count, rngTmp.Columns.Count).FormulaArray = f
Else
rngInsert.Formula = f
End If
End Sub

VBA to create formula based on another variable

I am trying to create the formula below using vba in excel
=SUM(COUNTIF(E7,"Vac")+ COUNTIF(E7,"LWOP")+COUNTIF(R7,"Vac")+ COUNTIF(R7,"LWOP"))
But E7 and R7 will change based on another variable called rCell.address
Below is the code that I have within the macro and it is giving an error:
Range("a8").Formula = "=SUMIF(countif(" & rCell.Address & ", "VAC"" & "))"
The current macro is:
Sub Find()
Dim strdate As String
Dim rCell As Range
Dim lReply As Long
With Worksheets("Sheet1")
strdate = .Range("a1").Value
End With
If strdate = "False" Then Exit Sub
strdate = Format(strdate, "Short Date")
On Error Resume Next
Set rCell = Cells.Find(What:=CDate(strdate), After:=Range("A1"), LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
On Error GoTo 0
If rCell Is Nothing Then
lReply = MsgBox("Date cannot be found. Try Again", vbYesNo)
If lReply = vbYes Then Run "FindDate":
End If
Range("a8").Formula = "=SUMIF(countif(" & rCell.Address & ",VAC" & "))"
End Sub
I am assuming that your error appears on this line of code: Range("a8").Formula = "=SUMIF(countif(" & rCell.Address & ",VAC" & "))".
You should change that line to
Range("a8").Formula = "=SUM(COUNTIF(" & rCell.Address & "," & Chr(34) & "Vac" & Chr(34) & ")+ COUNTIF(" & rCell.Address & "," & Chr(34) & "LWOP" & Chr(34) & ")+COUNTIF(" & rCell.Offset(0, 13).Address & "," & Chr(34) & "Vac" & Chr(34) & ")+ COUNTIF(" & rCell.Offset(0, 13).Address & "," & Chr(34) & "LWOP" & Chr(34) & "))"
Updated with better answer thanks to KS Sheon
Range("a8").Formula = "=SUM(COUNTIF(" & rCell.Address & ",""Vac"")+ COUNTIF(" & rCell.Address & ",""LWOP"")+COUNTIF(" & rCell.Offset(0, 13).Address & ",""Vac"")+ COUNTIF(" & rCell.Offset(0, 13).Address & ",""LWOP""))"
SUMIF is wrong in this context.
Range("a8").Formula = "=SUMIF(countif(" & rCell.Address & ",VAC" & "))"
you should use SUMIF like this
Range("a8").Formula =SUMIF(B2:B25,">5")

Unexpected run time error 1004. PDF not saving to folder

I have some code to pdf and save my file to a folder on my computer. I've tested in the past and had no problem. However, after making some minor changes i am getting run time error 1004. Any ideas on why this is? Very frustrating. Thank you.
Private Sub CommandButton2_Click()
Application.ScreenUpdating = False
Dim i As Long
Dim ws As Worksheet
Dim FileName As String
Set ws = Sheets("Multi")
Set wsJob = Sheets("Job")
FileName = ws.Range("B2")
LastRow = ws.Range("B" & Rows.Count).End(xlUp).Row
For i = 8 To LastRow
wsJob.Activate
wsJob.Range("AZ1").Value = ws.Range("B" & i)
wsJob.Range("AZ2").Value = ws.Range("C" & i)
wsJob.Range("AZ3").Value = ws.Range("D" & i)
wsJob.Range("AZ4").Value = ws.Range("E" & i)
wsJob.Range("AZ5").Value = ws.Range("F" & i)
wsJob.Range("AZ6").Value = ws.Range("G" & i)
wsJob.ComboBox1.Visible = False
wsJob.ComboBox2.Visible = False
wsJob.ComboBox3.Visible = False
wsJob.ComboBox4.Visible = False
wsJob.ComboBox5.Visible = False
wsJob.ComboBox6.Visible = False
wsJob.CommandButton1.Visible = False
wsJob.Rows("4:13").EntireRow.Hidden = True
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=ws.Range("B2") & "TCC Analysis - " & ws.Range("B" & i) & " - " & ws.Range("C" & i) & " - " & ws.Range("D" & i) & " - " & ws.Range("E" & i) & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False
Next i
wsJob.ComboBox1.Visible = True
wsJob.ComboBox2.Visible = True
wsJob.ComboBox3.Visible = True
wsJob.ComboBox4.Visible = True
wsJob.ComboBox5.Visible = True
wsJob.ComboBox6.Visible = True
wsJob.CommandButton1.Visible = True
wsJob.Rows("4:13").EntireRow.Hidden = False
ws.Activate
Application.ScreenUpdating = True
End Sub
Replace this line;
FileName:=ws.Range("B2") & "TCC Analysis - " & ws.Range("B" & i) & " - " & ws.Range("C" & i) & " - " & ws.Range("D" & i) & " - " & ws.Range("E" & i) & ".pdf"
with this;
FileName:=ws.Range("B2").value & "TCC Analysis - " & ws.Range("B" & i).value & " - " & ws.Range("C" & i).value & " - " & ws.Range("D" & i).value & " - " & ws.Range("E" & i).value & ".pdf"
Replace;
wsJob.Range("AZ1").Value = ws.Range("B" & i)
wsJob.Range("AZ2").Value = ws.Range("C" & i)
wsJob.Range("AZ3").Value = ws.Range("D" & i)
wsJob.Range("AZ4").Value = ws.Range("E" & i)
wsJob.Range("AZ5").Value = ws.Range("F" & i)
wsJob.Range("AZ6").Value = ws.Range("G" & i)
with this;
wsJob.Range("AZ1").Value = ws.Range("B" & i).Value
wsJob.Range("AZ2").Value = ws.Range("C" & i).Value
wsJob.Range("AZ3").Value = ws.Range("D" & i).Value
wsJob.Range("AZ4").Value = ws.Range("E" & i).Value
wsJob.Range("AZ5").Value = ws.Range("F" & i).Value
wsJob.Range("AZ6").Value = ws.Range("G" & i).Value
Replace
FileName = Sheets("Multi").Range("B2")
with this
FileName = Sheets("Multi").Range("B2").value
Change FileName decleration with different string because FileName is also using in the ActiveSheet.ExportAsFixedFormat line...

Compare excels and copy rest of Information

I was working with optimisation of code and after review from man people asked me to use Option Explicit and define Variables for everything and shorten the code. Which i did to maximum possible But the below code copies data from another excel by asking path and copy some specific data in column V and W. Also there is formula which compare data and find exact rows and which need to be copy.
Now please help how should i optimise this code and give variables to it.
Or please provide code in which we can compare 2 excel for example: A2:E is same then it should copy H2:I
For Each ws In MainWB.Worksheets
If ws.Name <> "Sap Data" And ws.Name <> "Automated BL Import" Then
With MainWB.Worksheets(ws.Name)
.Range("V1").Value = "When it will be Cleared or Action Taken/Required"
.Range("W1").Value = "Backup Link"
LastRow = MainWB.Worksheets(ws.Name).Range("B" & Rows.Count).End(xlUp).Row
.Range("Q1:Q" & LastRow).Delete
End With
End If
Next ws
b = MsgBox("Do you want to update comments for current postings from previous month?" & vbCrLf & vbCrLf & "Note:- If are runing this macro for the 1st time plese choose option 'No'", _
vbYesNo + vbQuestion, "Question")
If b = vbYes Then
Filename = Application.GetOpenFilename(, , "Please select previous month BL comment file to update comments.", , False)
If Filename <> "False" Then
Workbooks.Open Filename, Format:=2
End If
updatesheet = ActiveWorkbook.Name
For Each ws In MainWB.Sheets
If ws.Name <> "Sap Data" And ws.Name <> "Automated BL Import" Then
For Each ds In Workbooks(updatesheet).Sheets
If ds.Name = ws.Name Then
LastRow = MainWB.Worksheets(ws.Name).Range("B" & Rows.Count).End(xlUp).Row
With MainWB.Worksheets(ws.Name)
.Range("T2:T" & LastRow).Formula = "=IFERROR(IF(VLOOKUP(RC[-1],'[" & updatesheet & "]" & ws.Name & "'!R2C[-1]:R1048576C,2,0) = 0,"""",VLOOKUP(RC[-1],'[" & updatesheet & "]" & ws.Name & "'!R2C[-1]:R1048576C,2,0)),"""")"
.Range("U2:U" & LastRow).Formula = "=IFERROR(IF(VLOOKUP(RC[-2],'[" & updatesheet & "]" & ws.Name & "'!R2C[-2]:R1048576C,3,0) = 0,"""",VLOOKUP(RC[-2],'[" & updatesheet & "]" & ws.Name & "'!R2C[-2]:R1048576C,3,0)),"""")"
.Range("V2:V" & LastRow).Formula = "=IFERROR(IF(VLOOKUP(RC[-3],'[" & updatesheet & "]" & ws.Name & "'!R2C[-3]:R1048576C,4,0) = 0,"""",VLOOKUP(RC[-3],'[" & updatesheet & "]" & ws.Name & "'!R2C[-3]:R1048576C,4,0)),"""")"
.Range("W2:W" & LastRow).Formula = "=IFERROR(IF(VLOOKUP(RC[-4],'[" & updatesheet & "]" & ws.Name & "'!R2C[-4]:R1048576C,5,0) = 0,"""",VLOOKUP(RC[-4],'[" & updatesheet & "]" & ws.Name & "'!R2C[-4]:R1048576C,5,0)),"""")"
.Range("X2:X" & LastRow).Formula = "=IFERROR(IF(VLOOKUP(RC[-5],'[" & updatesheet & "]" & ws.Name & "'!R2C[-5]:R1048576C,6,0) = 0,"""",VLOOKUP(RC[-5],'[" & updatesheet & "]" & ws.Name & "'!R2C[-5]:R1048576C,6,0)),"""")"
.Range("T2:X" & LastRow).Value = MainWB.Worksheets(ws.Name).Range("T2:X" & LastRow).Value
End With
Your bottom part is a mess, you are missing some end ifs, You are missing the dims for the variables
The first part of the code is below.
You need to explain what you are trying to do with the second part of the code.
Sub Button1_Click()
Dim wb As Workbook, ws As Worksheet
Dim bk As Workbook, sh As Worksheet
Set wb = Workbooks("ThisOne.xlsm")
For Each ws In wb.Sheets
If ws.Name <> "Sap Data" And ws.Name <> "Automated BL Import" Then
With ws
.Range("V1").Value = "When it will be Cleared or Action Taken/Required"
.Range("W1").Value = "Backup Link"
LastRow = ws.Range("B" & Rows.Count).End(xlUp).Row
.Range("Q1:Q" & LastRow).Delete'?
End With
End If
Next ws
b = MsgBox("Do you want to update comments for current postings from previous month?" & vbCrLf & vbCrLf & "Note:- If are runing this macro for the 1st time plese choose option 'No'", _
vbYesNo + vbQuestion, "Question")
If b = vbYes Then
Filename = Application.GetOpenFilename(, , "Please select previous month BL comment file to update comments.", , False)
If Filename <> "False" Then
Workbooks.Open Filename, Format:=2
End If
Else: Exit Sub
End If
Set bk = ActiveWorkbook
' updatesheet = ActiveWorkbook.Name'what is this for?
For Each sh In bk.Sheets
' If sh.Name <> "Sap Data" And ws.Name <> "Automated BL Import" Then
' For Each ds In Workbooks(updatesheet).Sheets
' If ds.Name = ws.Name Then
' LastRow = MainWB.Worksheets(ws.Name).Range("B" & Rows.Count).End(xlUp).Row
' With MainWB.Worksheets(ws.Name)
' .Range("T2:T" & LastRow).Formula = "=IFERROR(IF(VLOOKUP(RC[-1],'[" & updatesheet & "]" & ws.Name & "'!R2C[-1]:R1048576C,2,0) = 0,"""",VLOOKUP(RC[-1],'[" & updatesheet & "]" & ws.Name & "'!R2C[-1]:R1048576C,2,0)),"""")"
' .Range("U2:U" & LastRow).Formula = "=IFERROR(IF(VLOOKUP(RC[-2],'[" & updatesheet & "]" & ws.Name & "'!R2C[-2]:R1048576C,3,0) = 0,"""",VLOOKUP(RC[-2],'[" & updatesheet & "]" & ws.Name & "'!R2C[-2]:R1048576C,3,0)),"""")"
' .Range("V2:V" & LastRow).Formula = "=IFERROR(IF(VLOOKUP(RC[-3],'[" & updatesheet & "]" & ws.Name & "'!R2C[-3]:R1048576C,4,0) = 0,"""",VLOOKUP(RC[-3],'[" & updatesheet & "]" & ws.Name & "'!R2C[-3]:R1048576C,4,0)),"""")"
' .Range("W2:W" & LastRow).Formula = "=IFERROR(IF(VLOOKUP(RC[-4],'[" & updatesheet & "]" & ws.Name & "'!R2C[-4]:R1048576C,5,0) = 0,"""",VLOOKUP(RC[-4],'[" & updatesheet & "]" & ws.Name & "'!R2C[-4]:R1048576C,5,0)),"""")"
' .Range("X2:X" & LastRow).Formula = "=IFERROR(IF(VLOOKUP(RC[-5],'[" & updatesheet & "]" & ws.Name & "'!R2C[-5]:R1048576C,6,0) = 0,"""",VLOOKUP(RC[-5],'[" & updatesheet & "]" & ws.Name & "'!R2C[-5]:R1048576C,6,0)),"""")"
' .Range("T2:X" & LastRow).Value = MainWB.Worksheets(ws.Name).Range("T2:X" & LastRow).Value
' End With
' End If
' Next ds
' End If
Next sh
End Sub