I have the following which is working in the same workbook how do I get this to use a summary sheet in a different workbook?
Sub SummurizeSheets()
Dim ws As Worksheet
Application.ScreenUpdating = False
Sheets("Summary").Activate
For Each ws In Worksheets
If ws.Name <> "Summary" Then
ws.Range("D2:D6, D8:D15").Copy
Worksheets("Summary").Cells(Rows.Count, 4).End(xlUp).PasteSpecial (xlPasteValues)
End If
Next ws
End Sub
Make sure you place the sub-routine in a Module, and not in
ThisWorkbook. You can insert a new module by right-clicking on workbook name (from the VBA editor) and going to Insert > Module.
Make sure the workbooks you want to use/reference are open.
Make sure the workbooks are all located in the same workbook collection. This is not a problem unless you manually create an additional instance of Excel.
Reference the workbooks using the Workbooks() object just like you
do with Worksheets.
Sub test()
Dim b2 As Workbook 'We will use this variable as a reference to the external workbook that contains the "Summary" worksheet.
Set b2 = Excel.Workbooks("testbook2") 'We assign the external workbook (which I named "testbook2" for the purposes of this example) to our 'b2' variable.
Dim ws1 As Worksheet
Dim ws2 As Worksheet 'We will use these variables as references to the worksheets we're using.
Set ws1 = Excel.ActiveSheet 'We set ws1 to equal our current sheet (which presumably is where you'll be copying data from).
Set ws2 = b2.Worksheets("Summary") 'We set ws2 to equal the sheet (named "Summary") in the external workbook (named "testbook2").
ws1.Range("D2:D6").Copy 'We copy the data from the active sheet, which we reference using our 'ws1' variable.
'Note: I had issues with using multiple ranges in the same object so I removed this from your code.
ws2.Cells(Rows.Count, 4).End(xlUp).PasteSpecial xlPasteValues 'You only need to use the ws2 variable since we've already defined it as the "Summary" sheet you want.
End Sub
I'm not sure why I follow that first rule, but I seem to remember having issues when using ThisWorkbook in conjunction with external workbook references.
Update
I edited the code to show you a better example of how to do this. You almost never need to use "Activate" or "Select" commands in VBA. Just assign variables and reference the values directly.
Related
I want to name a worksheet in excel as the value inside cell "C6" in the tab named "Control". I am new to VBA and what I tried was typing this on a module.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'
' Macro2 Macro
'
'
Dim month As String
month = Sheet2.Range("C5")
Sheets("Month").Name = month
End Sub
Moreover, I do not know whether the name will be updated automatically. I do not want to have to run a macro to change the worksheet name...
Thanks!
It sounds like you want to be able to always refer to the same worksheet, regardless of the worksheet's name changing (as shown on the worksheet's tab) .
This is where the worksheets' CODENAME Property comes in handy.
Let's say you have an object variable declare for your worksheet like Dim ws As Worksheet. You can refer to a worksheet three basic ways.
...by Name :
Set object variable:
Set ws = Sheets("Sheet1")
The worksheet name is the only worksheet identifier that can be changed to whatever you want, which (as you're probably aware) is done like:
ws.Name = "NewSheetname"
...or alternatively, like:
Sheets("Sheet1").Name = "NewSheetName"
...by Index Number :
The index number identifies the position of the worksheet's "tab", compared to the others (and cannot be changed without changing the order of the worksheets)
Set object variable:
Set ws = Sheets(1)
...then you could (still) change the worksheets name like:
ws.Name = "NewSheetname"
...or you could change the name by referring to the worksheet index number like:
Sheets(1).Name = "NewSheetName"
NOTE: If the worksheet is moved (or another worksheet is inserted before it), the Index number will change! Therefore, it's usually not the preferred method of referring to a worksheet.
...by CodeName :
The CodeName is how Excel refers to the worksheets internally. It is the original name that Excel gave the worksheet, and it does not change since it is a read-only property.
Set object variable:
Set ws = Sheet1
...then you could (still) change the worksheets name like:
ws.Name = "NewSheetname"
...or you could change the name by referring to the worksheet codename like:
Sheet1.Name = "NewSheetName"
You can check a worksheets' CodeName property like:
MsgBox Sheets("YourSheetName").CodeName
...or, if ws is already referencing the worksheet:
MsgBox ws.CodeName
So, in your case, you could change the name of your worksheet as often as you like, with:
Sheet2.Name = "NewNameHere"
...just keep referring to it as Sheet2.
One more example to clarify the difference:
Create a new workbook. (It will automatically have worksheet named Sheet1.)
Change the worksheet name to "Sheet1999", either manually (by double-clicking the name on it's tab) or programmatically (with Sheet1.Name="Sheet1999")
Now, if you want to find out how many rows on that sheet have been used, you use use either:
MsgBox Sheets("Sheet1999").UsedRange.Rows.Count
...or:
MsgBox Sheet1.UsedRange.Rows.Count
A note about Sheets versus Worksheets:
When referring to a worksheet Sheets and Worksheets can usually be used interchangeably, so for example these two lines do the same thing:
Worksheets("mySheet").Calculate
Sheets("mySheet").Calculate
The difference is that:
the Worksheets object searches the Worksheets Collection for a matching Name, Index, or CodeName.
the Sheets object searches the Worksheets Collection **and the Charts Collection** for a matching Name, Index, or CodeName.
Therefore, the only time it would be a problem is if you have a chart and a worksheet with the same name.
So, don't ever name a chart the same as a worksheet, and then you won't have to worry about it, and can go on saving 4 keystrokes any time you refer to a Sheet... :)
More Information:
MSDN : Worksheet Object
MSDN : Worksheet Properties
MSDN : Worksheet Methods
MSDN : Sheets Object
Sub Save7()
Dim NextRow As Range
Set NextRow = Range("AC" & Sheets("Sheet1").UsedRange.Rows.Count)
Sheet3.Range("AC14:AG14").Copy
Sheet1.Activate
NextRow.PasteSpecial Paste:=xlValues, Transpose:=False
Application.CutCopyMode = False
Set NextRow = Nothing
End Sub
My purpose of this code is to copy data ( Five columns of 'NO' in AC14 to AG14) from sheet 3 and paste to sheet 1 where the last active cell is at.
The code above is working well, however I made some modification to the sheet tab name for sheet 1. Sheet 1 is now called "Equipment stuffs", while sheet 3 name is remaining unchanged.
After those changes, the macro stopped working. The cause is probably because I don't know how to declare "Equipment stuffs" in the code .
There's no need to do copy/paste to move data from one place on the spreadsheet to another. You should simply assign the Value of the respective Range objects, for example:
Sheet1.Range("NamedRange2").Value = Sheet1.Range("NamedRange2").Value
Also, use code names for the sheets, instead of Sheets("SheetName"), and defined named for the ranges, instead of Range("AC14:AG14", otherwise your code will stop working if the user renames the sheet or inserts or deletes any rows above your reference.
If you want to automate this a little you could collect the active workbook and loop through each sheet using wb.Worksheets. Then collect the name with targetSheet.Name.
Option Explicit
Public Sub getSheet()
Dim wb As Workbook
Dim targetSheet As Worksheet
Set wb = ActiveWorkbook
For Each targetSheet In wb.Worksheets
Debug.Print targetSheet.Name
Next targetSheet
End Sub
I’m brazilian hehe, I understood your question , I’ve a code for alter the data in same worksheet (I’ll attach it here), for you to change the data in another worksheet, you need put on:
Worksheets("NameWorkSheet) Activate
for the VBA that’s refers to this tab.
I want to copy all the data and paste it in new workbook. With the below coding, I am able to paste all the values but it is creating two workbooks and pasting the data in one workbook.
I want to create only one new workbook and past the data. Not sure as to what went wrong.
On Error Resume Next
ThisWorkbook.Sheets(2).Copy
Dim wkb As Workbook
Set wkb = Workbooks.Add
wkb(1).PasteSpecial xlPasteValues
On Error GoTo 0
The Copy method has a different meaning when applied to a Worksheet and when applied to a Range:
The Copy method of a Worksheet creates a copy of the sheet; in the absence of any parameter, the copy is placed in a new workbook.
The Copy method of a Range puts a copy of the Range on the clipboard, from where you can then Paste it somewhere else.
So in your case, the statement
ThisWorkbook.Sheets(2).Copy
already makes a copy the Worksheet into a new workbook.
If you want to create the new workbook explicitly then you should copy the used range to the clipboard:
ThisWorkbook.Sheets(2).UsedRange.Copy
It's not the answer, but let me do it instead of yourself:
On Error Resume Next
ThisWorkbook.Sheets(2).Copy
Dim wkb As Workbook
Set wkb = Workbooks.Add
wkb(1).PasteSpecial xlPasteValues
On Error GoTo 0
.
I have a question regarding the correct address of Workbooks in VBA, which I am fairly new to.
Here is what I have done so far:
I have written a sub that, amongst other things, creates a worksheet with the CodeName "table10".
Then I defined a function to manipulate the contents of said sheet: this function
Text_To_Numbers(worksheet as worksheet)
expects a worksheet argument. I call the function from another sub using the following line:
Call Text_To_Numbers(table10)
Now, here is my issue:
The above works flawlessly when the only open workbook is the one I want to manipulate with my function. However, when I have multiple open workbooks, the function will try to manipulate a different workbook, resulting in an error.
I am quite certain that there must be a way to specify the workbook to be used, but I am unable to find it. That being said, there is another complication: The name of the workbook which I would like to manipulate is machine generated, so it always has a different name. This means that using an explicit reference to the same file name time and again is not an option.
Could anybody help me resolve this?
You need to fully qualify objects in VBA to avoid situations like this where it is ambiguous what the parent is.
In your situation, you want the sheet to be connected to its parent workbook, so make sure you specify that it came from a given workbook!
You cannot directly refer to worksheets in other workbooks by their CodeName, this can only be done to the ThisWorkbook object (the workbook containing the VBA code). See the question Fully reference a worksheet by codename for details on how to get the sheet by its codename from another workbook. I have included the function in the answer and how to use it in this context.
You created the sheet table10 in one of the following:
ActiveWorkbook
ThisWorkbook
WB (some workbook object)
So you can access it using that workbook object without a need for the name!
Using ThisWorkbook.table10 should give same behaviour as just table10, but here are two neater examples for calling the function.
' A neater way to call the function:
Text_To_Numbers worksheet:=ThisWorkbook.table10
' You could also call it simply using
Text_To_Numbers ThisWorkbook.table10
If your sheet is not within ThisWorkbook
' Get sheet (from the workbook object you are using, WB) and pass to your Text_To_Numbers
Text_To_Numbers GetSheetWithCodename("table10", WB)
Function GetSheetWithCodename(ByVal worksheetCodename As String, Optional wb As Workbook) As Worksheet
Dim iSheet As Long
If wb Is Nothing Then Set wb = ThisWorkbook ' mimics the default behaviour
For iSheet = 1 To wb.Worksheets.Count
If wb.Worksheets(iSheet).CodeName = worksheetCodename Then
Set GetSheetWithCodename = wb.Worksheets(iSheet)
Exit Function
End If
Next iSheet
End Function
Try assigning the workbook and sheet to a variable then calling it in this way when you need to do some work in it:
Dim WB As Workbook
Dim WS As Worksheet
'If you want to open the workbook before doing work
Set WB = Workbooks.Open("/Workbook path name goes here”)
Set WS = WB.Worksheets("Table10")
Then you just need to pass a call to the WS variable from within your function to perform operations within the specified sheet.
Edit:
Apologies, didn't realise you were trying to reference the index name in the project editor when I first read your question. The code name can be referenced from an external workbook with the following example which shows how to select the workbook and sheet codename to perform a copy/paste from one workbook to another:
Sub UseCodeNameFromOutsideProject()
Dim WS As Worksheet
With Workbooks("MyWorkbook.xlsb")
Set WS = _
.Worksheets(CStr(.VBProject.VBComponents("Sheet1").Properties(7)))
WS.Range("A1").Copy
Selection.Copy
WS.Range("B1").PasteSpecial
End With
End Sub
Thanks to Enderland for the idea.
So I currently have three workbooks, I have created a folder in my Desktop, and where I am using workbook x, through a range on a cell to open up workbook called m (old) and workbook called n (new). I am then updating the old with the new.
Problem
Once I have opened up m, I am having to do a save as of the file as a newname. I am keen to know is there way of referring to it without using the workbook newname, as this workbook name would be concatenated with today's date and the name can be quite long and time consuming to type. I have produced several subroutines, one to remove protection etc,. and one for carrying out the coping actions and I am calling the subroutines, I just want to now if there is way of linking the newsaved name to some of the subroutines from referencing. Alternatively the old file could be saved at the very end. I am keen to pursue this avenue as I will be playing in certain other cases with four workbooks.
I have taken this code and amended it, but I am unable to open both spreadsheets, the strange thing when i block out the code and go through a test both work for each path they work, but not at the same time.
this is the code i amended, which i was able to find in
Dim x As Workbook, y As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Set x = Workbooks.Open("path to copying book")
Set y = Workbooks.Open("path to pasting book")
Set ws1 = x.Sheets("Sheet you want to copy from")
Set ws2 = y.Sheets("Sheet you want to copy to")
With ws1
.Cells.Copy ws2.cells
y.Close True
x.Close False
End With
End Sub
this is my code where it is not opening both workbooks
Dim wb as Workbook
Dim wb1 As Workbook, wb2 As Workbook
Dim ws as Worksheet, ws1 As Worksheet, ws2 As Worksheet
Dim Lst As Long,
Dim r1, r2 As Range
Set wb = ThisWorkbook
Set wb1 = Workbooks.Open("Sheets("x").Range("A4").Value")
Set wb2 = Workbooks.Open("Sheets("x").Range("A5").Value")
With wb2
Call Wbkunprtect()
I would be grateful for some help, please for those who are trigger happy can you hold back from pressing the down arrow some of us are not excel knowledgeable and also trying to learn and do not want to be banned from asking questions, I am trying to move data between two workbooks wb1 and wb2, through another wb i have completed my code, and this is the bit which stopping me from going forward.
I have learned a great deal from this site the reason I asked certain questions as I am reluctant to use select or activate as I have been told this is a bad habit you have to keep away from.
From what I understood, you'll need to use a WorkBook object! the WorkBook object will have the instance of the newly added workbook. It is as simple as that:
Sub example_new_workbook()
Dim wb As Workbook
Set wb = Workbooks.Add
wb.SaveAs ("path where you want to save")
End Sub
That way, "wb" will have the instance of the new workbook, and you can use freely to reference that new workbook. Remember, the WorkBooks object holds all the instances of all open workbooks, so you can get the reference for any other workbook through this object.
As to make it "Global", you can declare it outside the "Sub" scope, so the variable will be permanent as long as the module (or wherever you put your code) is open like this:
public wb as Workbook
Sub <your_routines>()
...
End Sub