VBA Error 'Subscript out of Range' - vba

I am trying to create a copy of a large macro enabled (xlsm) file in xlsx format.
Sub Button1_Click()
Dim wb As Workbook
Set wb = Workbooks.Open("C:\original.xlsm")
Dim mySheetList() As String
ReDim mySheetList(0 To (ThisWorkbook.Sheets.Count) - 1)
Dim a As Integer
a = 0
For Each ws In ActiveWorkbook.Worksheets
mySheetList(a) = ws.Name
a = a + 1
Next ws
'actually save
Worksheets(mySheetList).Copy
ActiveWorkbook.SaveAs Filename:="ORIGINAL_COPY.xlsx" 'default ext
wb.Close
End Sub
I am getting subscript out of range error at following line:
mySheetList(a) = ws.Name

You are sizing the array with ThisWorkbook.Sheets but the loop use ActiveWorkbook.Worksheets. You need the same reference to avoid issues when multiple workbooks are opened.

You're using 4 different references to workbooks:
wb, ThisWorkbook and ActiveWorkbook are not necessarily the same thing. Furthermore, when you use Worksheets without prefixing it with a workbook reference, you're implicitly referencing the Activeworkbook. And, when you use Worksheets.Copy without any arguments, you're implictly creating a new workbook.
Currently, if ThisWorkbook has fewer sheets than original.xlsm, then your array will not be large enough to accommodate indexes larger than the count of sheets in ThisWorkbook. That is what is causing your out of bounds error.
I've adjusted the code. This will open the XLSM, copy the sheets, save the new XLSX workbook, and close the original XLSM, leaving the new XLSX workbook open.
Sub Button1_Click()
Dim wbOriginal As Workbook
Dim wbOutput As Workbook
Set wbOriginal = Workbooks.Open("C:\original.xlsm")
Dim mySheetList() As String
ReDim mySheetList(0 To (wbOriginal.Sheets.Count) - 1)
Dim a As Integer
a = 0
For Each ws In wbOriginal.Worksheets
mySheetList(a) = ws.Name
a = a + 1
Next ws
'Unfortunately, Worksheets.Copy isn't a function, so it doesn't
'return the workbook that it creates, so we have to execute the
'copy, then find the activeworkbook
Worksheets(mySheetList).Copy
Set wbOutput = ActiveWorkbook
'actually save
wbOutput.SaveAs Filename:="ORIGINAL_COPY.xlsx" 'default ext
wbOriginal.Close
End Sub

Why bother with all that looping?
Sub MM()
Dim sourceWB As Excel.Workbook
Set sourceWB = Workbooks.Open("C:\Original.xlsm")
sourceWB.SaveAs "C:\ORIGINAL_COPY.xlsx", FileFormat:=xlOpenXMLWorkook
sourceWB.Close False '// Optional
End Sub
The .SaveAs() method would be far more effective.
As mentioned in other answers, your issue seems to be with wb, ActiveWorkbook and ThisWorkbook being used interchangeably when they are actually different things.
wb is a workbook object that has been set to "C:\original.xlsm". It will always refer to that workbook unless you close the workbook, empty the object, or assign a new object to it.
ActiveWorkbook refers to the workbook that is currently active in Excel's forefront window. (i.e. The workbook you can see on your screen)
ThisWorkbook refers to the workbook in which the currently executing code belongs to. To quickly explain the difference:
Workbook A is the only workbook open, and has some code in to open another workbook (let's call it Workbook B).
At the moment, Workbook A is the ActiveWorkbook.
The code in workbook A starts running, workbook A is now the ActiveWorkbook and ThisWorkbook (because the running codes resides in this workbook)
The code opens Workbook B, which naturally opens in the forefront of Excel. Now Workbook B is the ActiveWorkbook and Workbook A is still the ThisWorkbook
Hopefully that clears it up a bit for you...

Related

VBA Copy Worksheet to a Different Open Workbook

I keep getting an Out of Range error when trying to copy a sheet from on workbook to another. The original spreadsheet (Master_Data.xlsm) is what is running the vba script. The scripts opens another spreadsheet, manipulates it, then copies the final sheet to be pasted in the Master_Data.xlsm Workbook.
Sub Result_Scrapper()
Dim wb As Workbook, ws As Worksheet, wbFile As Object
Dim masterBook As Workbook
Dim wsa As Worksheet
Dim year As Integer
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.GetFolder("C:\Users\Output_Spreadsheets\")
Set masterBook = Excel.Workbooks("Master_Data.xlsm")
Application.ScreenUpdating = False
For Each wbFile In fldr.Files
If fso.GetExtensionName(wbFile.Name) = "xlsm" Then
Set wb = Workbooks.Open(wbFile.Path)
'Copy sheet of interest
ActiveSheet.Copy 'Before:=ThisWorkbook.Sheets(“A”) 'tried doing it using before statement but it also caused errors
'paste sheet into masterBook spread--this is where the error comes
masterBook.Sheets(Sheets.Count).Paste
End If
masterBook.Sheets("master").Name = Right([A2], 30)
Next wbFile
There are two issues. First, as someone else commented, you need to fully qualify the count. Second, you'll want to do it on one line; and you could do before, but then you're just pushing out whatever that last sheet is, if you add it after, then the sheets stay in order.
Try:
ActiveSheet.Copy After:=masterBook.Sheets(masterBook.Sheets.Count)

Stay in the active workbook after opening other workbooks

I am trying to open two other Excel workbooks to take data to do my calculation through the macro. I have a working code to open those files.
Dim wbCount As Integer
Application.ScreenUpdating = False
For wbCount = 1 To 2
Workbooks.Open Filename:=ThisWorkbook.Path & "\Installation Sheet " & wbCount & ".xlsm", UpdateLinks:=False
Next wbCount
ThisWorkbook.Activate
Application.ScreenUpdating = True
The other files are named "Installation Sheet 1" and "Installation Sheet 2". After this code runs, I end up with "Installation Sheet 1" displaying instead of my active workbook.
Put your ActiveWorkbook into a variable at the appropriate place and then use that to move back. ThisWorkbook is the one with code in. So be sure if you mean ActiveWorkbook or ThisWorkbook, or if ThisWorkbook is the ActiveWorkbook at the time. In that case, you can simply Set wb = ThisWorkbook
Dim wb As Workbook
Set wb = ActiveWorkbook
'Set wb = ThisWorkbook '<== If you want the workbook containing the code
'Other code
wb.Activate
You have to put your workbooks references into variables and then using these variables you have two options: close newly opened workbook, so only original stays opened or use Activate method to bring the original workbook to front.
Sample code:
Sub OpeningWb()
Dim wb As Workbook, currentWb As Workbook
Set currentWb = ThisWorkbook
Set wb = Workbooks.Open("your path here")
' if you want to close opened workbook
'wb.Close
' if you want to bring to front original workbook
currentWb.Activate
End Sub
Alternatively, you can do the following:
Dim wbToDisplay As Workbook
Set wbToDisdplay = Workbooks("workbook name here")
wbToDisplay.Activate
The above solutions didn't work for me, because activate method is fired before second workbook is displayed, so I get active this second workbook always. My workaround is wait a couple of seconds before calling Activate method:
Dim t: t = Timer
While Timer < t + 2 'wait for 2 seconds
DoEvents
Wend
ThisWorkbook.Activate

Subscript Out Of Range when accessing Sheet in another opened Workbook

I want to reference to the first opened Workbook. 2 workbooks are open: one that is calling the macro to execute, and the workbook which contains the macro. Somehow, the code runs smoothly very often. But sometimes, there occurs a referencing error when accessing data in the first opened workbook: Subscript Out Of Range.
On this line, the error occurs:
Set mastersheet = Workbooks(1).Sheets("Setting")
So there should be two workbooks in the collection. What am I overseeing? Please keep in mind, that the first opened workbook doesn't have a fixed name, so the name of the open workbook changes. The second Workbook, the workbook which contains the macro to execute, doesn't change it's name.
Unfortunately, you don't provide more code or any information about what kind of code "container" the macro is in. The following solution assumes the macro is in a Worksheet or Workbook code container (Sheet1 or ThisWorkbook in the VBA Editor, for example).
It's possible to get the workbook from the code container. If the code is in a Worksheet code container, then use Me.Parent. If it's in ThisWorkbook use Me. These containers are actually classes that represent the Worksheet / the Workbook object. So Me refers to that object. The parent of a Worksheet is its workbook.
So a Workbook object is set to its container workbook. Then the open workbooks are looped in a For...Each and the workbook is tested whether it's the same as the code container workbook, or if it's another. If it's another, then the loop is exited. Debug.Print shows the result (two different names) and demonstrates how to continue to work with the separate workbook objects.
Sub GetOtherWorkbook()
Dim wbWithMacro As Workbook
Dim wbOther As Workbook, wb As Workbook
Set wbWithMacro = Me.Parent 'Assumes macro is in a "Sheet" code container
'Set wbWithMacro = Me 'Assumes macro is in "ThisWorkbook" code container
For Each wb In Workbooks
If Not wb Is Me Then
Set wbOther = wb
Exit For
End If
Next
Debug.Print wbWithMacro.Name, wbOther.Name
End Sub
I suggest the following to find the Setting worksheet:
Option Explicit
Public Sub FindSettingWorksheet()
Dim MasterSheet As Worksheet
Dim wb As Workbook
For Each wb In Workbooks 'loop through all open workbooks
On Error Resume Next 'stop error reporting
Set MasterSheet = wb.Worksheets("Setting") 'if this throws an error it's the wrong workbook
On Error GoTo 0 're-enable error reporting
If Not MasterSheet Is Nothing Then Exit For 'if we found the setting worksheet we can exit/stop
Next wb
If Not MasterSheet Is Nothing Then 'test if we found it
Debug.Print MasterSheet.Name
Else
Debug.Print "Settings not found"
End If
End Sub

Excel synchronize workbooks with vba

I'd like to ask if you could help me with copying some worksheet data from workbook A into my active workbook (workbook B)
I have the following code in the main workbook to copy the data from workbook A
Public Sub Worksheet_Activate()
test
End Sub
Sub test()
Dim Wb1 As Workbook
Dim MainBook As Workbook
'Open All workbooks first:
Set Wb1 = Workbooks.Open("Z:\Folder\WorkbookA.xlsm")
'Set MainBook = Workbooks.Open(Application.ActiveWorkbook.FullName)
Set MainBook = Application.ActiveWorkbook
'Now, copy what you want from wb1:
Wb1.Sheets("Projekte").Cells.Copy
'Now, paste to Main worksheet:
MainBook.Worksheets("Projekte").Range("A1").PasteSpecial xlPasteAll
Application.CutCopyMode = False
'Close Wb's:
Wb1.Close SaveChanges:=False
End Sub
I know, that it opens worksheet A and that it highlights and copys the data.
The script wont paste it into worksheet B (where the script is executed from)
Anybody know what i did wrong?
Kindest regards, and thanks for any help !
You should set the Mainbook (destination) first before the origin (if you're going to use ActiveWorkbook).
'Set MainBook First
Set MainBook = ThisWorkbook
'Open All workbook:
Set Wb1 = Workbooks.Open("Z:\Folder\WorkbookA.xlsm")
Just for clarity, it's just me being OC on this one.
you have to properly reference your workbook and worksheet objects
if you have to paste the whole content of range (including formatting, comments, ...), then you want to code like follows (explanations in comments):
Option Explicit
Sub test()
Dim targetSheet As Worksheet
Set targetSheet = ActiveSheet 'store currently active sheet
Workbooks.Open("Z:\Folder\WorkbookA.xlsm").Sheets("Projekte").UsedRange.Copy Destination:=targetSheet.Range("A1") ' open the wanted workbook and copy its "Projekte" sheet used range to 'targetSheet (i.e.: the sheet in the workbook where it all started) from its cell A1
ActiveWorkbook.Close SaveChanges:=False ' close the currently active workbook (i.e. the just opened one)
End Sub
if you only need to paste values, then this is the way to go (much faster!):
Option Explicit
Sub test()
Dim targetSheet As Worksheet
Set targetSheet = ActiveSheet 'store currently active sheet
With Workbooks.Open("Z:\Folder\WorkbookA.xlsm").Sheets("Projekte").UsedRange ' open the wanted workbook and reference its sheet "Projekte" used range
targetSheet.Range("A1").Resize(.Rows.Count, .Columns.Count).Value = .Value
.Parent.Parent.Close SaveChanges:=False 'close the parent workbook of referenced range (i.e., the newly opened workbook)
End With
End Sub
My recommendation is never to use ActiveWorkbook.
In most cases when people use ActiveWorkbook they actually meant to use ThisWorkbook. The difference is:
ActiveWorkbook is the currently selected one which is "on top of the screen" in exact that moment when your code runs. That can be any workbook the user just clicked on while your code runs. So you never can be 100% sure to get the right workbook.
ThisWorkbook is the actual workbook your code runs at the moment. And this doesn't change ever. So this is a well defined reference and no gamble about which workbook is on top at the moment.
About why your approach did not work
Set Wb1 = Workbooks.Open("Z:\Folder\WorkbookA.xlsm") 'this line makes WorkbookA the active one
Set MainBook = Application.ActiveWorkbook 'this makes MainBook = WorkbookA
Therefore a simple Set MainBook = Application.ThisWorkbook should work here.
Another recommendation
Sheets and Worksheets is not the same. Make sure you never use Sheets when you can use Worksheets.
Sheets contains worksheets and charts
Worksheets contain only worksheets
An example Sheets(1).Range("A1") fails if it is a chart.

Runtime Error Subscript out of range

Basically am trying to copy a sheet from one workbook to another. While doing that i get an error called subscript out of range.
Sub cp()
Dim ws As Worksheet, wb As Workbook
'Target workbook
Set wb = Workbooks("Desktop:\Book2.xlsb")
'Source workbook
For Each ws In Workbooks("Desktop:\Book1.xlsb")
ws.copy After:=wb.Sheets(wb.Sheets.Count)
Next ws
End Sub
If the file is already open, then just do:
Set wb = Workbooks("Book2.xlsb")
And likewise,
For each ws in Workbooks("Book1.xlsb").Worksheets
Note also you need to indicate the .Worksheets collection in the above statement. For each ws in Workbooks("Book1.xlsb") will not work, even though a workbook contains worksheets, there is no implied iteration like this, you need to specify which collection you're looping over.