Workbook_Open Subscript out of Range - vba

I am having issues with writing a macro in VBA when it is being initiated with the opening of my workbook. The error reads 'Error 9 - Subscript out of range'.
The Macro should look to see if there is a 'control' sheet in the current workbook, if not then it will open another workbook and copy the control sheet over - closing that workbook as it does so.
This is a strange one because it actually works if I attach it to a button, but doesn't work when I try and initiate the Macro when you open the file.
Here is my code;
Private Sub Workbook_Open()
' CreateEUC Macro
ScreenUpdating = False
For i = 1 To Worksheets.Count
If Worksheets(i).Name = "Control" Then
exists = True
MsgBox ("There is already an EUC slide in this workbook")
End If
Next i
If Not exists Then
' Open Location
Workbooks.Open "T:\Pricing\EUC Inventory\EUC Control Sheet v0.4.xlsx"
' Copy/Paste EUC
Sheets("Control").Copy After:=ThisWorkbook.Sheets(1)
' Close EUC Workbook
Workbooks("EUC Control Sheet v0.4.xlsx").Close savechanges:=False
' Move sheet at front of workbook
Sheets("Control").Move Before:=Sheets(1)
Range("A1:H1").Select
End If
ScreenUpdating = True
End Sub

As you haven't qualified which workbook contains worksheet "Control", you're implicitly referring to the activeworkbook, and you've already proven that worksheet "Control" doesn't exist... Qualify your worksheet reference (oh, and always declare your variables!)
Private Sub Workbook_Open()
Dim i As Integer
Dim exists As Boolean
Application.ScreenUpdating = False
For i = 1 To Worksheets.Count
If Worksheets(i).Name = "Control" Then
exists = True
MsgBox ("There is already an EUC slide in this workbook")
End If
Next i
If Not exists Then
With Workbooks.Open("T:\Pricing\EUC Inventory\EUC Control Sheet v0.4.xlsx") ' Open Location
.Sheets("Control").Copy After:=ThisWorkbook.Sheets(1) ' Copy/Paste EUC
.Close savechanges:=False ' Close EUC Workbook
End With
Sheets("Control").Move Before:=Sheets(1) ' Move sheet to front of workbook
Range("A1:H1").Select
End If
Application.ScreenUpdating = True
End Sub

Related

Save after Sheets.Copy without using ActiveWorkbook

I don't like using ActiveWorkbook. Is it possible to rewrite the following code without using ActiveWorkbook while also sticking to Sheets.Copy
Sub test()
ThisWorkbook.Sheets(Array("Lists", "Input", "ListsPars")).Copy
ActiveWorkbook.SaveAs "Palim.xlsx"
ActiveWorkbook.Close
End Sub
Sub test()
With Workbooks.Add ' add a new workbook and reference it
ThisWorkbook.Sheets(Array("Lists", "Input", "ListsPars")).Copy after:=.Worksheets(1) ' copy wanted sheets from 'ThisWorkbook' after reference workbook first sheet
Application.DisplayAlerts = False ' prevent alert coming form subsequent sheet deletion statament
.Worksheets(1).Delete ' delete referenced workbook first sheet
Application.DisplayAlerts = True 'restore alerts back on
.SaveAs "Palim.xlsx" ' save referenced workbook
.Close ' close referenced workbook
End With
End Sub

Deactivate entire sheet selection after paste

I recently asked a question and received a great answer on this site, but I am now running into a different problem. The code below works well for running through each workbook in a folder, copying a sheet's contents, and pasting those contents into a master workbook exactly how I would like:
Sub ConslidateWorkbooks()
'Code to pull sheets from multiple Excel files in one file directory
'into master "Consolidation" sheet.
Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Dim wbName As String
With ActiveSheet
Range("A1").Activate
End With
Application.ScreenUpdating = False
FolderPath = ActiveWorkbook.Path & "\"
Filename = Dir(FolderPath & "*.xls*")
wbName = ActiveWorkbook.Name
Do While Filename <> ""
If Filename <> wbName Then
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
copyOrRefreshSheet ThisWorkbook, Sheet
Next Sheet
Workbooks(Filename).Saved = True
Workbooks(Filename).Close
ActiveSheet.Range("A1").Activate
End If
Filename = Dir()
Loop
Application.ScreenUpdating = True
End Sub
Sub copyOrRefreshSheet(destWb As Workbook, sourceWs As Worksheet)
Dim ws As Worksheet
On Error Resume Next
Set ws = destWb.Worksheets(sourceWs.Name)
On Error GoTo 0
If ws Is Nothing Then
sourceWs.Copy After:=destWb.Worksheets(destWb.Worksheets.Count)
Else
ws.Unprotect Password:="abc123"
ws.Cells.ClearContents
sourceWs.UsedRange.Copy
ws.Range(sourceWs.UsedRange.Address).PasteSpecial (xlPasteAll)
Application.CutCopyMode = False
End If
End Sub
The problem I am having now: After the paste is completed, each sheet in the master workbook has all of its cells selected, as though I Ctrl+A'd the entire sheet. I would like to get rid of this. It is a small task which I tried to accomplish in the line ActiveSheet.Range("A1").Activate within the Do While .. loop, but it has not worked for me.
EDIT:
I found a solution that works in this case. I am not sure why this was necessary, because the comments and answers in this thread seem like they should work, but they did not. I call this sub before I turn screenupdating to True in the main sub:
Sub selectA1()
Worksheets(1).Activate
Dim Sheet As Worksheet
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Activate
ActiveWindow.ScrollRow = 1
ActiveWindow.ScrollColumn = 1
Sheet.Range("A1").Select
Next Sheet
Worksheets(1).Activate
End Sub
I realize this is more complicated than it should be, but it works for my purposes.
In your copy sub, add in another code in the loop that will select a cell which should deactivate the total used range selection and just select the coded range.
Sub copyOrRefreshSheet(destWb As Workbook, sourceWs As Worksheet)
Dim ws As Worksheet
On Error Resume Next
Set ws = destWb.Worksheets(sourceWs.Name)
On Error GoTo 0
If ws Is Nothing Then
sourceWs.Copy After:=destWb.Worksheets(destWb.Worksheets.Count)
Else
ws.Unprotect Password:="abc123"
ws.Cells.ClearContents
sourceWs.UsedRange.Copy
ws.Range(sourceWs.UsedRange.Address).PasteSpecial (xlPasteAll)
ws.range("A1").select
Application.CutCopyMode = False
End If
End Sub
I added ws.range("A1").select which should do as I described above.

Excel VBA - Copy method of Worksheet class failed

I am trying to copy sheets from VBA. Here is my code:
'Create a new excel workbook and copy two result sheets.
Public Function copyAsSaveResultSheets(filePath As String)
'Remove alert for confirmations
Application.DisplayAlerts = False
'Get new work book
Dim newWorkBook As Workbook
Set newWorkBook = Workbooks.Add
'Copy result sheet
'When click "Debug" cursor is here.
ThisWorkbook.Sheets("ResultProcess").Copy Before:=newWorkBook.Sheets(1)
ThisWorkbook.Sheets("ResultCode").Copy Before:=newWorkBook.Sheets(1)
'Delete default sheet
For Each sheet In Worksheets
Select Case sheet.Name
Case "Sheet1", "Sheet2", "Sheet3"
sheet.Delete
End Select
Next
'Save work book
newWorkBook.SaveAs filePath
'Close new work book
ActiveWorkbook.Close
'Available showing alert from application
Application.DisplayAlerts = True
End Function
When running this code, I get this error:
I didn't find any error in my code. The "ResultProcess" sheet and "ResultCode" sheet are protected according to requirement. Does this matter?

VBA: Auto save&close out of all current workbooks except for Macro workbook

I'm trying to close all currently open Workbooks except for my Macro workbook, and .SaveAs my path, but I want my path to be a specified cell within my macro workbook [D1] to be precise. I also want the file name to be saved as cell A1 in the Workbook that I'm currently saving and closing out of. Now I'm stuck. I've listed the code that I'm utilizing currently, and the issue I'm running into with this piece of code is that it's saving as the name in cell A1 in the currently selected Workbook vs the Workbook the code is currently cycling on. I hope this makes sense.
Option Explicit
Public ThisFile As String
Public Path As String
Sub CloseAndSaveOpenWorkbooks()
Dim Wkb As Workbook
' ThisFile = ActiveWorkbook.Sheets(1).Range("A1").Value ** Commented out as this piece of code was not working as intended **
Path = "C:\Users\uuis\Desktop"
With Application
.ScreenUpdating = False
' Loop through the workbooks collection
For Each Wkb In Workbooks
With Wkb
If .Name <> ThisWorkbook.Name Then
' if the book is read-only
' don't save but close
If Not Wkb.ReadOnly Then
.SaveAs Filename:=(Path & "\" & ActiveWorkbook.Sheets(1).Range("A1").Value & ".xls"), FileFormat:=xlExcel8
End If
' We save this workbook, but we don't close it
' because we will quit Excel at the end,
' Closing here leaves the app running, but no books
.Close
End If
End With
Next Wkb
.ScreenUpdating = True
' .Quit 'Quit Excel
End With
End Sub
ActiveWorkbook.Sheets(1).Range("A1").Value
should be
Wkb.Sheets(1).Range("A1").Value

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.