VBA: Referencing a Worksheet in the Active Workbook - vba

While this seems very basic, I am continually getting an error message while trying to select a cell in a certain sheet on my workbook in my Macro. Does any one know why this will not work? I'm getting error message Run Time Error '1004'.
The sheets name is "Sheet1"and my code is below:
Application.ActiveWorkbook.Worksheets("Sheet1").Range("N2").Select

It's bad practice to use ActiveWorkbook when you don't need to. It's always better to set your workbooks and worksheets to actual variables that you can call on. I think your code is activating another workbook then trying to select a range in a worksheet it can't find.
Sub TryThis()
Dim wbk As Workbook
Dim ws As Worksheet
Set wbk = Workbooks("myWorkbook.xlsm")
Set ws = wbk.Worksheets("Sheet1")
'Now when we say "ws." it is actually "Workbooks("myWorkbook.xlsm").Worksheets("Sheet1")."
'This is okay to start with but it's better to work with the cells directly
ws.Select
Range("N2").Select
Selection = "myText"
'This is much faster and you won't have to worry about what is currently selected
ws.Range("N2") = "myText"
End Sub

Related

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

Subscript out of range Midcoded error

Usually with a subscript out of range error, something is misspelled. This time I can guarantee that it is not misspelled. I am declaring workbook and sheets names as variables to be used later for simple copy paste stuff. But when I define one of my sheets as Set main=wb.Sheets("Primary") I get the error, subscript out of range. I did't believe it, so I copied what I wrote and pasted that as the Sheet name. Same error. Therefore, their must be an issue with how I set up my Workbook/Worksheets. Any help much appreciated.
Sub copyPaste()
Dim wb As Workbook
Dim main As Sheets
Dim hypo As Sheets
Set wb = ThisWorkbook
Set main = wb.Sheets("Primary")
Set hypo = wb.Sheets("Hypo")
Application.CutCopyMode = False
wb.main.Range("D22:D46").Value = wb.main.Range("D22:D46").Value
End Sub
You want Worksheet (singular) not Sheets (plural) (Sheets is a collection of worksheets)
Dim main As WorkSheet
Dim hypo As WorkSheet
and here you dont use the workbook object because it's already defined as part of the worksheet reference. Change it to this
main.Range("D22:D46").Value = main.Range("D22:D46").Value

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.

vba create a new sheet and change name

I am a VBA new user. My purpose is copy a existing worksheet to a new one. And then change the new worksheet name to a proper name. However, I got the VBA Error Message like,
vba runtime error 9 subscript out of range(at the line Set new_ws =Active...)
The VBA code will be the following; thanks in advance
Sub CreateWS()
Dim ws As Worksheet
Dim new_ws As Worksheet
Set ws = ActiveWorkbook.Worksheets("Bus Voltage")
ws.Name = "Bus Voltage_All"
ws.Copy Worksheets(Sheets.Count)
Set new_ws = ActiveWorkbook.Worksheets("Bus Voltage_All(2)")
new_ws.Name = "Bus Voltage"
End Sub
It looks to me like you have an issue with a space.
Your line Set new_ws = ActiveWorkbook.Worksheets("Bus Voltage_All(2)")
Should be
Set new_ws = ActiveWorkbook.Worksheets("Bus Voltage_All (2)")
Notice the space after _All? You were missing that in your code.
A (potentially) helpful tidbit is that when you use the .Copy method, your new worksheet is automatically activated, so you can use this code instead (to avoid errors with the space):
ws.Copy Worksheets(Sheets.Count)
Set new_ws = ActiveSheet
And, on the topic of referencing sheets at all (though not directly related to your question), you can use something called the CodeName to reference the sheet.
For example:
The CodeNames are Sheet1, Sheet2, etc.
The code:
Worksheets("Old Data").Activate
And
Sheet1.Activate
are equivalent.
The major benefit to referencing sheets this way is that if your worksheet name changes, your code won't break.

Excel Macro: Copy and paste worksheet into another worksheet

I've been able to make an exact copy of a worksheet and add it to the workbook with:
Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Detailed List")
ws1.Copy ThisWorkbook.Sheets(Sheets.Count)
End Sub
but I'm trying to have the copied worksheet paste over another worksheet. For example, I'm trying to copy the worksheet "Detailed List" and have it paste and overwrite "Testing Sheet", but all I'm able to do with the code above is make another worksheet. Any help would be great.
You nearly had it, and your own solution works...however, in the efforts of completeness...
Sub Test()
Dim ws1 As Worksheet
Dim ws1Copy As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Detailed List")
ws1.Copy ThisWorkbook.Sheets(Sheets.Count) 'we can't set the copied object directly to a varaiable, but it becomes the active sheet by default
Set ws1Copy = ActiveSheet 'assign the newly copied activesheet to a variable
Application.DisplayAlerts = False 'supress warnings, the delete method gives the user a warning
Sheets("Testing Sheet").Delete 'delete the testing sheet
Application.DisplayAlerts = True 'un-supress the warnings
ws1Copy.Name = "Testing Sheet" 'change the name of the copied sheet to the testing sheet.
End Sub
So I ended up doing this:
Worksheets("Detailed List").Range("A7").CurrentRegion.Copy
Worksheets("Detailed Copy").Range("A7").PasteSpecial
I first just copied the Detailed List before I started running the macro. Then I highlighted all the data points and titles, and overwrite the Copy. I needed to do this because I am making a macro that whenever someone changes a cell in the "Detailed List", I need to display the Old Value that used to be in the cell, so by having essentially two copies of the List, I can first make the comparisons, and then just copy the list over and over, so it automatically updates itself to any changes that have been made.