Excel VBA - Unable to duplicate worksheet in another workbook - vba

From a workbook, I am attempting to open another workbook, duplicate the master worksheet in that workbook and rename it. The problem being that no matter what I try it doesn't seem to work when I Copy the master sheet.
Attempt One - Using the copy method.
Sub individualStats()
'Initialize
Dim app As New Excel.Application
app.Visible = False
Dim objWorkbook As Excel.Workbook
Set objWorkbook = app.Workbooks.Add("S:\MH\Stats\Jordan Individual Stats.xlsm")
'Test if Worksheet exists already
Set wsTest = Nothing
On Error Resume Next
Set wsTest = objWorkbook.Worksheets("Test Worksheet")
On Error GoTo 0
'If worksheet does not exist then duplicate Master and rename
If wsTest Is Nothing Then
objWorkbook.Worksheets("Master").Copy After:=objWorkbook.Worksheets(Worksheets.count)
' ^ This is the line I get the error on.
ActiveSheet.Name = "Test Worksheet"
End If
'Save and close workbook.
app.DisplayAlerts = False
objWorkbook.SaveAs Filename:="S:\MH\Stats\Jordan Individual Stats.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
objWorkbook.Close SaveChanges:=False
app.Quit
Set app = Nothing
app.DisplayAlerts = True
End Sub
I have marked the line I get the error on. The error is
"Run-time error '9': Subscript out of range."
Attempt Two - Calling a Macro from the Workbook
Inside of the "Jordan Individual Stats.xlsm" workbook I have created this Macro.
Sub duplicateMaster()
Sheets("Master").Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = "Test Worksheet"
End Sub
This sub works completely fine if I run it within that workbook.
But when I try to call this module from the original workbook it doesn't work.
...
If wsTest Is Nothing Then
Application.Run ("'S:\MH\Stats\Jordan Individual Stats.xlsm'!duplicateMaster")
End If
...
The error comes up on the line in the duplicateMaster module on the line "Sheets("Master").Copy After:=Sheets(Sheets.Count)".
The error is the same "Run-time error '9': Subscript out of range."
How can I fix this?

objWorkbook.Worksheets("Master").Copy _
After:=objWorkbook.Worksheets(Worksheets.count)
here Worksheets.count will refer to the active workbook, but not in the new instance of Excel you created. It will instead refer to the active workbook in the instance where your code is running.
Try this:
objWorkbook.Worksheets("Master").Copy _
After:=objWorkbook.Worksheets(objWorkbook.Worksheets.count)
You don't need to create a new instance of Excel to do this, and not doing so will prevent this type of easily-overlooked problem.

Related

Call "ThisWorkbook"

I am trying to switch between a template (hard coded) and a dynamic report which changes name weekly (ThisWorkbook). I am struggling with calling the variable x to bring focus to the workbook. I am copying the template formulas and pasting them into the dynamic report.
Sub wkbk()
Dim x As Excel.Workbook
Set x = ThisWorkbook
Dim pth As String
pth = x.FullName
Windows(pth).Activate
End Sub
Here is the VBA code I am using:
Windows("BBU_CMD_TEMPLATE.xlsx").Activate
Cells.Select
Selection.Copy
Windows(pth).Activate
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Paste
Why not just use ThisWorkbook.Activate? There's generally no need to assign a variable to represent a built-in like ThisWorkbook so the rest of those variables are unnecessary unless you're using them elsewhere in that procedure (from the snippet provided, you aren't, so you don't need them).
Sub wkbk()
ThisWorkbook.Activate
End Sub
However, what's the point of wkbk procedure? If solely to activate the workbook, that's not needed either and there are plenty of reasons to avoid Activate.
Sub CopySheetFromTemplateToThisWorkbook()
Dim tmplt As Workbook
On Error Resume Next
Set tmplt = Workbooks("BBU_CMD_TEMPLATE.xlsx")
If tmplt Is Nothing Then
MsgBox "Template file needs to be open..."
Exit Sub
End If
On Error GoTo 0
With ThisWorkbook
tmplt.ActiveSheet.Copy After:=.Sheets(.Sheets.Count)
End With
End Sub

VBA excel protecting sheets

I created a spreadsheet where on Work Book Open Event i create a sheet called "Hello". This works perfectly fine. The problem arises when I Protect the structure of the WORKBOOK with password. Now when i open my workbook and try to add the sheet to it, the application gives me an error on this line of code where I'm adding the sheet. All my code below
Private Sub Workbook_Open()
Dim ws As Worksheet
Dim i As Integer
Dim isHELLOexist As Boolean
isHELLOexist = False
For i = 1 To Worksheets.Count
If Worksheets(i).Name = "HELLO" Then
isHELLOexist = True
End If
Next i
If isHELLOexist = False Then
Set ws = Sheets.Add '''here's where i get an error with ADDING sheet
ws.Name = "HELLO"
End If
End Sub
Now this code works perfectly fine as long as STRUCTURE of workbook is not protected with password. What should i do here to get this to work?
ERROR states:
METHOD ADD OF OBJECT SHEETS FAILED ERROR 1004
Figured it out....I first need to unprotect the workbook, add the sheet and protect it again like this...
thisworkbook.unprotect("password")
If isHELLOexist = False Then
Set ws = Sheets.Add '''here's where i get an error with ADDING sheet
ws.Name = "HELLO"
End If
thisworkbook.protect("password"),true,true

excel VBA error: The object invoked has disconnected from its clients

It seems a normal question and I have searched and tried many suggestions here but the error persists. I want to copy a "case1" sheet from current workbook to an existing workbook(file name is "workbook2.xlsx", it has a worksheet named "case2"), then save the workbook and close it. Sometimes it works well, but most of the time I kept getting the same error. In fact I did not change any code so I don't know where went wrong.
The error shows "The object invoked has disconnected from its clients". It always breaks in the same place:
ThisWorkbook.Sheets("case1").Copy Before:=ActiveWorkbook.Sheets("Case2")
Sub CopySheet()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'open existing "workbook2.xlsx"
Workbooks.Open filename:="c:\workbook2.xlsx"
'copy a sheet named "case1" from current workbook to "workbook2.xlsx" which already has a sheet named "case2"
ThisWorkbook.Sheets("case1").Copy Before:=ActiveWorkbook.Sheets("Case2")
'close "workbook2.xlsx"
Workbooks("workbook2.xlsx").Activate
ActiveWorkbook.Close SaveChanges:=True
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Always set references to sheets and workbooks, then there is no chance of confusing which is which. This code does the same thing and should not give you any errors.
Sub CopySheet()
Dim wb1 As Workbook, ws1 As Worksheet 'Source
Dim wb2 As Workbook, ws2 As Worksheet 'Target
Set wb1 = ThisWorkbook
Set ws1 = wb1.Sheets("case1")
Set wb2 = Workbooks.Open("c:\workbook2.xlsx")
Set ws2 = wb2.Sheets("case2")
ws1.Copy Before:=ws2
wb2.Close True
End Sub

Excel: Copy workbook to new workbook

So prior to asking this I searched and found something that was similar to what I was looking to do here.
Basically I have workbook AlphaMaster. This workbook is a template that I want to use to create new workbooks from weekly.
In this workbook there are sheets named: Monday-Saturday and additional sheets with a corresponding date for Mon, Tues, ect.
I have created a Form that loads on open of the workbook. What I want is when I click form run it will:
Run Code saving template as new workbook
Rename workbook based of input from userform1
Rename the workbooks with proper weekday
Workbook is named for a week end date dates of 6 sheets would renamed after this(example week ending 5th of Jan.) is put into user form as:
WeekEnd: Jan-5-2014
Dates
Mon:Dec.30
Tues:Dec.31
Weds:Jan.1
Thurs:Jan.2
Fri:Jan.3
Sat:Jan.4
Than click command. so far this is what I have:
Private Sub CommandButton1_Click()
Dim thisWb As Workbook, wbTemp As Workbook
Dim ws As Worksheet
On Error GoTo dummkopf
Application.DisplayAlerts = False
Set thisWb = ThisWorkbook
Set wbTemp = Workbooks.Add
On Error Resume Next
For Each ws In wbTemp.Worksheets
ws.Delete
Next
On Error GoTo 0
For Each ws In thisWb.Sheets
ws.Copy After:=wbTemp.Sheets(1)
Next
wbTemp.Sheets(1).Delete
wbTemp.SaveAs "blahblahblah\New.xlsx"
new.xlsx i want to be filled in from form
Vorfahren:
Application.DisplayAlerts = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Vorfahren
End Sub
Complications:
Currently while this does work I cant change the name of the document its named what I name it in the .saveAs area. I'm thinking I need to create an alternate function to handle this. Second, when it finishes my sheets are displayed in the reverse order of the template.
Some guidance/suggestions on where to go from here would be greatly appreciated!
A few issues here:
You cannot delete all Worksheets in a Workbook.
You should copy the sheet to the end to retain order (if the worksheets in source workbook is sorted):
For Each ws In thisWb.Sheets
ws.Copy After:=wbTemp.Sheets(wbTemp.Sheets.Count)
wbTemp.Sheets(wbTemp.Sheets.Count).Name = "NewSheetName" ' <-- Rename the copied sheet here
Next
If your source Worksheets does not have names "Sheet#" then delete the default sheets afterwards.
Application.DisplayAlerts = False
For Each ws In wbTemp.Sheets
If Instr(1, ws.Name, "Sheet", vbTextCompare) > 0 Then ws.Delete
Next
Application.DisplayAlerts = True
For SaveAs, refer to Workbook.SaveAs Method (Excel).
I use this in my application and works good
Set bFso = CreateObject("Scripting.FileSystemObject")
bFso.CopyFile ThisWorkbook.FullName, destinationFile, True
Once it's copied you can then open it in new Excel Object and do what ever you want with it.

Writing a string to a cell in excel

I am trying to write a value to the "A1" cell, but am getting the following error:
Application-defined or object-defined error '1004'
I have tried many solutions on the net, but none are working. I am using excel 2007 and the file extensiton is .xlsm.
My code is as follows:
Sub varchanger()
On Error GoTo Whoa
Dim TxtRng As Range
Worksheets("Game").Activate
ActiveSheet.Unprotect
Set TxtRng = ActiveWorkbook.Sheets("Game").Cells(1, 1)
TxtRng.Value = "SubTotal"
'Worksheets("Game").Range("A1") = "Asdf"
LetsContinue:
Exit Sub
Whoa:
MsgBox Err.number
Resume LetsContinue
End Sub
Edit: After I get error if I click the caution icon and then select show calculation steps its working properly
I think you may be getting tripped up on the sheet protection. I streamlined your code a little and am explicitly setting references to the workbook and worksheet objects. In your example, you explicitly refer to the workbook and sheet when you're setting the TxtRng object, but not when you unprotect the sheet.
Try this:
Sub varchanger()
Dim wb As Workbook
Dim ws As Worksheet
Dim TxtRng As Range
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
'or ws.Unprotect Password:="yourpass"
ws.Unprotect
Set TxtRng = ws.Range("A1")
TxtRng.Value = "SubTotal"
'http://stackoverflow.com/questions/8253776/worksheet-protection-set-using-ws-protect-but-doesnt-unprotect-using-the-menu
' or ws.Protect Password:="yourpass"
ws.Protect
End Sub
If I run the sub with ws.Unprotect commented out, I get a run-time error 1004. (Assuming I've protected the sheet and have the range locked.) Uncommenting the line allows the code to run fine.
NOTES:
I'm re-setting sheet protection after writing to the range. I'm assuming you want to do this if you had the sheet protected in the first place. If you are re-setting protection later after further processing, you'll need to remove that line.
I removed the error handler. The Excel error message gives you a lot more detail than Err.number. You can put it back in once you get your code working and display whatever you want. Obviously you can use Err.Description as well.
The Cells(1, 1) notation can cause a huge amount of grief. Be careful using it. Range("A1") is a lot easier for humans to parse and tends to prevent forehead-slapping mistakes.
I've had a few cranberry-vodkas tonight so I might be missing something...Is setting the range necessary? Why not use:
Activeworkbook.Sheets("Game").Range("A1").value = "Subtotal"
Does this fail as well?
Looks like you tried something similar:
'Worksheets("Game").Range("A1") = "Asdf"
However, Worksheets is a collection, so you can't reference "Game". I think you need to use the Sheets object instead.
replace
Range("A1") = "Asdf"
with
Range("A1").value = "Asdf"
try this instead
Set TxtRng = ActiveWorkbook.Sheets("Game").Range("A1")
ADDITION
Maybe the file is corrupt - this has happened to me several times before and the only solution is to copy everything out into a new file.
Please can you try the following:
Save a new xlsm file and call it "MyFullyQualified.xlsm"
Add a sheet with no protection and call it "mySheet"
Add a module to the workbook and add the following procedure
Does this run?
Sub varchanger()
With Excel.Application
.ScreenUpdating = True
.Calculation = Excel.xlCalculationAutomatic
.EnableEvents = True
End With
On Error GoTo Whoa:
Dim myBook As Excel.Workbook
Dim mySheet As Excel.Worksheet
Dim Rng As Excel.Range
Set myBook = Excel.Workbooks("MyFullyQualified.xlsm")
Set mySheet = myBook.Worksheets("mySheet")
Set Rng = mySheet.Range("A1")
'ActiveSheet.Unprotect
Rng.Value = "SubTotal"
Excel.Workbooks("MyFullyQualified.xlsm").Worksheets("mySheet").Range("A1").Value = "Asdf"
LetsContinue:
Exit Sub
Whoa:
MsgBox Err.Number
GoTo LetsContinue
End Sub