I've discovered that the code I have for pulling a template worksheet into an open workbook runs into problems that results in the code ThisWorkbook referencing the template, and not the open workbook.
pvt_obj_Workbook.Worksheets("Ten").Copy Before:=ThisWorkbook.Worksheets(1)
I'm trying to capture the open workbook name into a variable to try and get my macro to work properly. The target (open workbook) will have multiple locations and names, but the template worksheet will be stored in a static location.
Public Sub copyNetContentsFiveWorksheet()
On Error Resume Next
'#
'# declare private variables
'#
Dim pvt_obj_Workbook As Excel.Workbook
Dim pvt_obj_TargetWorkbook As Excel.Workbook
Dim pvt_str_WorksheetName As String
Const pvt_cstr_TemplateWorkbook As String = "P:\QC Sheets\PRO-B 4.4 FM 03 04 Line 4&5 QC sheets.xlsm"
pvt_obj_TargetWorkbook = ThisWorkbook
'#
'# prompt the user for the name to be given to the new worksheet after
'# the worksheet has been imported
'#
pvt_str_WorksheetName = InputBox("Please enter date and shift for new sheet" & Chr(13) & _
"eg.24-02-13-D or 24-02-13-N1." & Chr(13) & "DO NOT USE SLASHES ( \ or / )", "Add New Sheet")
If Len(pvt_str_WorksheetName & "") = 0 Then
Exit Sub
End If
'#
'# freeze application user interface for performance reasons and suppress any warnings issued
'#
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'#
'# open the workbook holding the template worksheet to copy - note that the constant variable must hold the full
'# path and name of the workbook, for example C:\TEMP\TEMPLATE.XLSX
'#
Set pvt_obj_Workbook = Workbooks.Open(pvt_cstr_TemplateWorkbook)
If pvt_obj_Workbook Is Nothing Then
MsgBox "Unable to open the template workbook at " & pvt_cstr_TemplateWorkbook, vbCritical, "Error message"
GoTo RoutineExit
End If
'#
'# copy the template worksheet and insert the worksheet into the current workbook before the
'# first existing worksheet
'#
pvt_obj_Workbook.Worksheets("Five").Copy Before:=pvt_obj_TargetWorkbook.Worksheets(1)
If Err.Number = 9 Then
MsgBox "No worksheet named Template exists in workbook " & pvt_cstr_TemplateWorkbook, vbCritical, "Error message"
GoTo RoutineExit
ElseIf Err.Number > 0 Then
MsgBox "Error " & Err.Number & " " & Err.Description & " occured while attempting to copy the template worksheet", _
vbCritical, "Error message"
GoTo RoutineExit
End If
'#
'# attempt to rename the newly inserted worksheet - if the rename fails, delete the copied template
'# worksheet
'#
pvt_obj_TargetWorkbook.Worksheets(1).Name = pvt_str_WorksheetName
If Err.Number > 0 Then
MsgBox "An error occured while trying to rename the imported worksheet to " & pvt_str_WorksheetName, vbCritical, "Error message"
ThisWorkbook.Worksheets(1).Delete
GoTo RoutineExit
End If
RoutineExit:
pvt_obj_Workbook.Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Any help would be greatly appreciated!
Bookmarks