Excel Select vs Activate
What is the difference between the VBA code wb.Sheets(1).Cells.Select
a开发者_开发问答nd wb.Sheets(1).Activate
?
Difference between select is that you can select several objects at once. Objects that are selected are also placed in the Selection object which you can use methods on. Unless you are selecting multiple objects, selecting (say, a cell) activates the object.
Activate just simply makes the object the active object. Best way to think of it is "many cells can be selected, but only one may be the active cell at any given time."
Note: They both have one thing in common - they are rarely ever needed and they do generally don't do anything but slow your code down. You can work directly on an object without selecting or activating it and it's best practice not to use these unless needed.
Here is an explanation from MSDN
You first example wb.Sheets(1).Cells.Select
allows you to select multiple cells
The second wb.Sheets(1).Activate
makes the sheet active.
There are lots of resources out there to help with Excel VBA.
http://www.excel-vba.com/index.htm#Tutorial%20on%20Excel%20Macros
http://www.excel-vba-easy.com/
http://www.functionx.com/vbaexcel/
The first selects all cells on the first sheet of the workbook wb. It will fail if the sheet is not active.
The second just activates the first sheet of the workbook wb. It does not alter the selection or activecell on that sheet, and in some cases there may be no selected range or activecell (eg. if there's an object on the sheet which is currently selected).
Select
- "Selects" Cell(s)
Activate
- "Activates" a sheet (kind of like saying to focus on a sheet)
Sometimes u need to specifically ACTIVATE
the sheet, in order to make a SELECT
I found this question while searching, I had the same question. Here is something I noticed:
Sub Transfer(x As Long)
Dim Rng, ID as Range
Dim i, j, n As Long
Worksheets(5).Activate
n = Worksheets(5).Range(Range("I88"), Range("I88").End(xlToRight)).Count
Worksheets(x).Select
Set Rng = Worksheets(3).UsedRange.Find("Element", LookIn:=xlValues).Offset(1, 1)
Set ElemID = Range(ElemRng.Offset(0, -1), ElemRng.Offset(0, -1).End(xlDown))
Set ElemRng = Worksheets(3).Range(ElemRng, ElemRng.End(xlToRight))
End Sub
I found that I HAD to put the worksheet.activate (or select) in or the code would run into:
Run-time error: '1004' Application-defined or object-defined error
Activate is often used for Sheets for Example. The Active sheet wil be shown on the screen... therfore there can only be one active sheet
Select though is can be used for multiple Cells for Example. Range(A1:B3).Select will select multiple cell which is'nt possible with activate
精彩评论