I want to pick up the data from the files, in which the particular worksheet exists. I have over 10 files; some don't contain the worksheet I am after. I've decided to skip them.
My code looks like this:
Sub CopyDataBetweenWorkbooks_Civils()
Dim wbSource As Workbook
Dim shTarget As Worksheet
Dim shSource As Worksheet
Dim strFilePath As String
Dim strPath As String
Dim i As Long
' Initialize some variables and
' get the folder path that has the files
Set shTarget = ThisWorkbook.Sheets("Civils Work Order")
strPath = GetPath
' Make sure a folder was picked.
If Not strPath = vbNullString Then
' Get all the files from the folder
strfile = Dir$(strPath & "*.xls", vbNormal)
Do While Not strfile = vbNullString
' Open the file and get the source sheet
Set wbSource = Workbooks.Open(strPath & strfile)
For i = 1 To Worksheets.Count
If Worksheets(i).Name = "Civils Work Order" Then
Set shSource = wbSource.Sheets("Civils Work Order")
End If
Next i
'Copy the data
Call CopyData_Civils(shSource, shTarget)
'Close the workbook and move to the next file.
wbSource.Close False
strfile = Dir$()
Loop
End If
End Sub
' Procedure to copy the data.
Sub CopyData_Civils(ByRef shSource As Worksheet, shTarget As Worksheet)
If shSource Is Nothing Then
On Error GoTo 0
Else
Const VHead As String = "A1:H1"
Const VMBom As String = "A2:H100"
shSource.Range(VHead).Copy
With shTarget.Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
End If
Dim lRow As Long
Dim i As Integer
lRow = shTarget.Cells(Rows.Count, "A").End(xlUp).Row + 1
If shSource Is Nothing Then
On Error GoTo 0
Else
shSource.Range(VMBom).Copy
With shTarget.Range("A" & lRow)
.PasteSpecial xlPasteValuesAndNumberFormats
.PasteSpecial xlPasteFormats
'.RemoveDuplicates Columns:=1, Header:=xlYes
.Sort Key1:=.Columns(1), Order1:=xlAscending, Header:=xlYes
.WrapText = True
End With
shTarget.Columns("A").ColumnWidth = 6.11
shTarget.Columns("B").ColumnWidth = 50
shTarget.Columns("C").ColumnWidth = 50
shTarget.Columns("D").ColumnWidth = 5.44
shTarget.Columns("E").ColumnWidth = 5.89
shTarget.Columns("F").ColumnWidth = 9
shTarget.Columns("G").ColumnWidth = 21.22
shTarget.Columns("H").ColumnWidth = 10.89
shTarget.Rows.EntireRow.AutoFit
For i = 3 To lRow Step 4
shTarget.Range(shTarget.Cells(i, 1), shTarget.Cells(i, 5)).Interior.Color = RGB(235, 235, 235)
shTarget.Range(shTarget.Cells(i, 7), shTarget.Cells(i, 8)).Interior.Color = RGB(235, 235, 235)
Next i
' Reset the clipboard.
Application.CutCopyMode = xlCopy
Call code_clearance_civils
End If
End Sub
Unfortunately, after the execution of several sheets, I receive an error:
Method 'Range of object'_Worksheet failed to point out the following line:
shSource.Range(VHead).Copy
How could I skip the workbooks, which don't have this worksheet and proceed as normal?
UPDATE:
When using WorksheetExists function, the error appears here: