Hi
Try this procedure (with function).
This procedure copies 'sheet1' from all sheets workbook in the LOGCALL directory, after the sheet that is active when the porcedure starts.
It checks that the sheet name to be used does not exist, and if it does trys the next number (upto 20), if sheet1 exists in the opened file.
Hope this hepls
Code:
Sub ImportSheets()
Dim Path As String
Dim filename As String
Dim sht As Worksheet
Dim wkB As Workbook
Dim i As Integer
Path = "C:\LOGCALL"
filename = Dir(Path & "\*.xls")
Application.ScreenUpdating = False
i = 1
Do While filename <> ""
'CHECK SHEET NAME TO BE CREATED DOES NOT EXIST
Do While SheetExists("Sheet" & i)
i = i + 1
If i = 20 Then
MsgBox "Too many sheets !", vbExclamation, "ERROR !!"
Application.ScreenUpdating = True
Exit Sub
End If
Loop
Set sht = ActiveSheet
Workbooks.Open filename:=Path & "\" & filename
If SheetExists("Sheet1") Then
Set wkB = ActiveWorkbook
Sheets("Sheet1").Copy After:=sht
ActiveSheet.Name = "Sheet" & i
i = i + 1
wkB.Close savechanges:=False
Else
MsgBox "Sheets1 does not exist in file '" & filename & "'", vbExclamation, "ERROR !!"
ActiveWorkbook.Close savechanges:=False
End If
filename = Dir
Loop
Application.ScreenUpdating = True
End Sub
Function SheetExists(ByVal sName As String)
Dim sht As Worksheet
SheetExists = True
For Each sht In ActiveWorkbook.Sheets
If sht.Name = sName Then Exit Function
Next sht
SheetExists = False
End Function
MTB