0% found this document useful (0 votes)
35 views17 pages

Referencing Cells & Ranges - 1

Uploaded by

akshay magar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
35 views17 pages

Referencing Cells & Ranges - 1

Uploaded by

akshay magar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 17
e glckal connect Excel and VBA Solutions (excell) oa . é » Contact (lexcel/index.php? option=com_contact&view=contact&id=11<emid=573) —_________. My Account (/excel/index php? (Search ‘option=com_content&view=article&id=3608temid=611) VBA Tutorial Login Hi prakash, Excel VBA Tutorial® Excel VBA Basics (/excel/index.php? option=com_content&vi icteai Excel VBA Objects (/excel/index.php? option=com_content&view=article&id=2768itemid=502) Working with Variables (lexcel/index. php? option=com_content8&view=article&id=2778itemid=504) Conditional Statements (excel/index. php? Excel Application Object (excel/index php? Workbooks & Worksheets (oxcel/index php? option=com_content8view=article&id=3378itemid=518) Excel VBA Cells & Ranges (excelVindex. php? rticle&id=2878itemid=523) Referencing Cells & Ranges - 1 (/excel/index. php?option=com_content&view=article&id=287&|temid=523) Referencing Cells & Ranges - 2 (lexcel/index. php?option=com_content&view=artcleBid=2888itomid=524) Find Method in Excel VBA (/excel/index.php?option=com_content&view=article&id=289&Itemid=526) \VBA - Last Used Row & Column (/excel/index. php?option=com_content&view=articleBid=2908temid=527) Text, String & Date Functions (lexcel/index php? rticle&id=2928itemid=531) Excel VBA Procedures (excel/index php? Excel VBA Arrays (lexcel/index. php? option=com_content&view=article&id=3318itemid=540) Error Handling & Debugging (excel/index php? option=com_content&view=article&id=3508itemid=542) Excel VBA Events (excel/index. php? option=com_content&view=article&id=3038Itemid=544) Custom Classes & Objects (excel/index. php? ActiveX & Form Controls, AutoShapes (excel/index. php? UserForms in Excel VBA (excel/index php? option=com_content&view=article&id=307&itemid=550) Charts in Excel VBA (/excellindex.php? option=com_content8view=article&id=3538itemid=603) Excel Pivot Tables with VBA (exceVindex. php? option=com_content&vie rticle&id=3328itemid=559) ‘Automation with VBA (lexcel/index. php? option=com_content&view=article&i 1=2498Itemid=575) Connect with Databases (ADO) (excel/index. php? rticle&id=2568Itemid=582) Connect with Databases (DAO) (excel/index php? rticle&id=2608itemid=587) Referencing Cells & Ranges - 1 Sok bk 2 Vote § vy) [Rate Article Index Referencing Cells & Ranges - 1 (/excel/index.php?option=com_content&view=article8id=287:referencing- cells-a-ranges-in-vba-1&catid=928ltemid=523&showall=8limitstart=) Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address (/excel/index.php?option=com_content&view=article&id=287:referencing-cells-2-ranges-in-vba- 18catid=928ltemid=523&showall=8limitstart=1) Activate & Select Cells; the ActiveCell & Selection (/excellindex.php? option=com_content&view=article&id=287:referencing-cells-a-ranges-in-vba- 1&catid=928itemid=523&showall=8limitstart=2) Entire Row/Column Properties, Inser option=com_content&view=articlegi jing Cells/Rows/Columns using Insert Method (/excel/index. php? 187:referencing-cells-a-ranges-in-vb: All Pages (lexcel/index. php?optior 1&catid=928ltemid=523&showall=18limitstart=) 7 :referencing-cells-a-ranges-in-vba- Excel VBA Referencing Ranges - Range, Cells, Item, Rows & Columns Properties; Offset; ActiveCell; Selection; Insert You can refer to or access a worksheet range using properties and methods of the Range object. A Range Object refers to a cell or a range of cells, It can be a row, a column or a selection of cells comprising of one or more rectangular J contiguous blocks of cells. One of the most important aspects in vba coding is referencing and using Ranges within a Worksheet. This section (divided into 2 parts) covers various properties and methods for referencing, accessing & using ranges, divided under the following chapters. Referencing Cells & Ranges - 1: Excel VBA Referencing Ranges - Range, Cells, Item, Rows & Columns Properties; Offset; ActiveCell; Selection; Insert: Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address; Activate & Select Cells; the ActiveCell & Selection; Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method: Referencing Cells & Ranges - 2: Excel VBA Refer to Ranges - Union & intersect; Areas, Current Region, UsedRange & End Properties; SpecialCells Method:- Ranges - Union & Intersect; Resize a Range; Referencing - Contiguous Block(s) of Cells, Range of Contiguous Data, Cells Meeting a Specified Criteria, Used Range, Cell at the End of a Block / Region, Last Used Row or Column; Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address ‘A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one (or more rectangular / contiguous blocks of cells. A Range object is always with reference to a specific worksheet, and Excel currently does not support Range objects spread over multiple worksheets. Rang fe ingle cell: Dim mg As Range ‘Set mg = Range("A1") Range object refers to a block of contiguous cells: Dim mg As Range Sef mg = Range("A1:C3°) Range object refers to a row. Dim mg As Range ‘Set mg = Rows(1) Range object refers to multiple columns: Dim mg As Range Sot mg = Columns("A:C") Range object refers to 2 or more blocks of contiquous cells - using the ‘Union method’ & ‘Selection’ (these have been explained in detail later in this section! Union method: Dim mgt As Range, mg2 As Range, mgUnion As Range ‘set a contiguous block of cells as the first range: Set mgt = Range("A1:B2") ‘set another contiguous block of cells as the second range: Sot mg2 = Rango(’D3:E4") ‘assign a variable (range object) fo represent the union of the 2 ranges, using the Union method: ‘Set mgUnion = Union(mgt, mg2) ‘set interior color for the range which is the union of 2 range objects: ‘mgUnion. Interior. Color = vbYellow Selection property: ‘select 2 contiguous block of cells, using the Select method: Range("A1:82,03:E4"),Solect ‘perform action (set interior color of cells to yellow) on the Selection, which is a Range object: ‘Selection. Interior. Color = vbYellow Range property of the Worksheet object ie. Worksheet. Range Property. Syntax: WorksheetObject. Range(Cell1, Cell2), You have an option to use only the Cell1 argument and in this case it wil have to be a At-style reference to a range which can include a range operator (colon) or the union operator (comma), or the reference to a range can be a defined name. Examples of using this type of reference are Worksheets(“Sheet1").Range("A1") which refers to cell A1, (or Worksheets("Sheet 1").Range("A1:83") which refers to the cells A1, A2, A3, 81, B2 & 83. When both the Cell1 & Cell2 arguments are used (cell1 and cell2 are Range objects), these refer to the cells at the top-left comer and the lower-right comer of the range (ie. the start and end cells of the range), and these arguments can be a single cell, an entire row or column or a single named cell. An example of using this type of reference is. Worksheets("Sheet”). Range(Cells(1, 1), Cells(3, 2)) which refers to the cells A1, A2, A3, B1, B2 & B3. Omitting the object qualifier will default to the active sheet viz. using the code Range("A1’) will return cell A1 of the active sheet, and will be the same as using Application. Range(’A1’) or ActiveSheet. Rango(’A1") Range property of the Range object: Use the Range. Range property [Syntax: RangeObject. Range(Cell1, Cell2)] {or relative referencing ie. to access a range relative to a range object. For example, Worksheets("Sheet1"). Range("C5:E8").Range("A1") will refer to Range(*CS") and Worksheets("Sheet1”). Range("C5:E8"). Range("B2’) will refer to Range("D6"). ‘Shortcut Range Reference: As compared to using the Range property, you can also use a shorter code to refer toa range by using square brackets to enclose an At-style reference or a name. While using square brackets, you do not type the Range word or wrap the range in quotation marks to make it a string. Using square brackets is similar to applying the Evaluate method of the Application object. The Range property or the Evaluate method use a string argument which enables you to manipulate the string with vba code, whereas using the square brackets will be inflexible in this respect. Examples: using (A7]. Value = 5is equivalent to using Range("A1"). Value = 5; using [A1:A3,B2:B4,C3:05}.Interior. Color = vbRed is equivalent to Range("A 1:3,B2:B4,C3:D5"). Interior. Color = vbRed, and with named ranges, [Score]. .nterior. Color = vbBlue is equivalent to Range("Score’).Interior.Color = vbBlue. Using square brackets only enables reference to fixed ranges which is a significant shortcoming. Using the Range property ‘enables you to manipulate the string argument with vba code so that you can use variables to refer to a dynamic range, as illustrated below: ‘Sub DynamicRangeVariable() ‘using a variable to refer a dynamic range. Dim i As Integer ‘enters the text "Hello" in each cell from B1 to BS: Fori=1T05 Range(" Next End Sub ‘The Cells Property retums a Range object referring to all cells in a worksheet or a range, as it can be used with respect to an Application object, a Worksheet object or a Range object. Application.Cells Property refers to all cells in the active worksheet. You can use the code Application.Cells or omit the object qualifier (this property is a member of 'globals') and use the code Calls to refer to all cells of the active worksheet. The Worksheet. Cells Property (Syntax: WorksheetObject.Celis) refers to all cells of a specified worksheet. Use the code Worksheets("Sheet1"). Cells to refer to all cells of worksheet named "Sheet". Use the Range.Cells Property ro refer to cells in a specified range - (Syntax: RangeObject Cells). This property can be used as Range("A1:85").Cells, however using the word cells in this case is immaterial because with or without this word the code will refer to the range A1:85. To refer to a specific cell, use the Item property of the Range object (as explained in detail below) by specifying the relative row and column positions after the Cells keyword, viz. Worksheets(*Sheet1").Colls.ltem(2, 3) refers to range C2 and Worksheets("Sheet"). Range("C2").Cells(2, 3) will refer to range E3. Because the Item property is the Range object's default properly you can omit the Item word word and use the code Worksheets("Sheet1”).Cells(2, 3) which also refers to range C2. You may find it preferable in some cases to use Worksheots("Sheet1").Colls(2, 3) over Worksheets("Sheet 1"), Range("C2") because variables for the row and column can easily be used therein Item property of the Range object: Use the Range.ltem Property to return a range as offset to the specified range. Syntax: RangeObject.\tem(Rowindex, Columnindex). The Item word can be omitted because Item is the Range object's default property. It is necessary to specify the Rowindex argument while Columnindex is optional. Rowindox is the index number of the cell, starting with 1 and increasing from left to right and then down. Worksheets("Sheet1").Cells.ltem(1) or Worksheets ("Sheet"). Cells(1) refers to range A1 (the top-left cell in the worksheel), Worksheets("Sheet1").Cells(2) refers to range B1 (cell next to the right of the top-left cell). While using a single-parameter reference of the Item property (je. Rowindex), if index exceeds the number of columns in the specified range, the reference will wrap to Successive rows within the range columns. Omitting the object qualifier will default to active sheet. Cells(16385) refers to range A2 of the active sheet in Excel 2007 which has 16384 columns, ‘and Cells(16386) refers to range B2, and so on. Also note that Rowindex and Columnindex are offsets and relative to the specified Range (ie. relative to the topeft comer of the specified range). Both Range("B3').Item(1) and Range("B3:06").tem(1) refer to range B3. The following refer to range D4, the sixth cell in the range: Range("B3:06").tem(6) or Range("B3:D6").Cells(6) or Range("B3:06")(6). Columnindex refers to the column number of the cell, can be a number starting with 1 or can be a string starting with the letter Worksheets("Sheet'").Cells(2, 3) and Worksheets("Sheet1).Cells(2, °C) both refer to range C2 wherein the Rowindex is 2 and Columnindex is 3 (column C). Range(*C2").Colls(2, 3) refers to range E3 in the active sheet, and Range("C2"),Cells(4, 5) refers to range GS in the active sheet. Using Range("C2").Item(2, 3) and Range("C2"). Item, 5) has the same effect and will refer to range E3 & range G5 respectively. Using Range("C2:D3"). Cells(2, 3) and Range("C2:D3"). Cells(4, 5) will also refer to range E3 & range G5 respectively. Omitting the Item or Cells word - Range("C2:03")(2, 3) and Range("C2:D3")/4, 5) also refers to range E3 & range G5 respectively. It is apparant here that you can refer to and retum cells outside the original specified range, using the Item property. Columns property of the Worksheet object: Use the Worksheet.Columns Property (Syntax: WorksheetObject. Columns) to refer to all columns in a worksheet which are retumed as a Range object. Example: Worksheets("Sheet1”). Columns will etum all columns of the worksheet; Worksheets “Sheet ").Columns(1) retums the first column (column A) in the worksheet; Worksheets("Sheot 1"), Columns("A’) retums the first column (column A); Worksheets("Sheet"). Columns(“A:C’) retums the columns A, B & C; and so on. Omitting the object qualifier will default to the active sheet viz. using the code Columns(1) will retum the first column of the active sheet, and will be the same as using Application. Columns(1), Columns property of the Range object: Use the Range.Columns Property (Syntax: RangeObject. Columns) to refer to columns in a specified range. Example: color cells from all columns of the specified range ie. B2 to D4: Worksheets("Sheet'"), Range("B2:D4"). Columns. interior. Color = vbYellow. Example2: color cells from first column of the range only ie. B2 to B4: Worksheets("Sheet1").Range("B2:D4").Colurins(1)..nterior.Color = vbGreen. If the specified range object contains multiple areas, the columns from the first area only wil be retumed by this property (Areas property has been explained in detail later in this section). Take the example of 2 areas in the specified range, first area being "B2:D4" and the second area being "F3:G6" - the following code will color cells from first column of the first area only ie. cells B2 to B4: Worksheets (“Sheet 1").Range("B2:04, F3:G6"). Columns(').Interior.Color = vbRed, Ornitting the object qualifier will default to active sheet - following will apply color to column A of the ActiveSheet: Columns(1).Interior. Color = vbRed. Use the Worksheet Rows Property (Syntax: WorksheetObject Rows) to refer to all rows in a worksheet which are retumed as a Range object. Example: Worksheets("Sheet1").Rows will retum all rows of the worksheet Worksheets("Sheet'"). Rows(1) retums the first row (row one) in the worksheet; Worksheels("Sheet").Rows(3) retums the third row (row three) in the worksheet; Worksheets ("Sheet 1"). Rows("3") returns the first 3 rows: and so on. ‘Omitting the object qualifier will default to the active sheet viz. using the code Rows(1) will rtum the first row of the active sheet, and will be the same as using Application. Rows(). Use the Range.Rows Property (Syntax: RangeObject Rows) to refer to rows in a specified range, Examplet: color cells from all rows of the specified range le. B2 to D4: Worksheets("Sheet 1").Range("B2:04"), Rows. Interior. Color = vbYellow. Example2: color cells from first row of the range only ie. B2 to D2: Worksheets("Sheet1"). Range("B2:D4").Rows(1). Interior. Color = vbGreen. If the specified range object contains multiple areas, the rows from the first area only will be retumed by this property (Areas property has been explained in detail later in this section). Take the example of 2 areas in the specified range, first area being "B2:D4" and the second area being "F3:G6" - the following code will color cells from first row of the first area only le. cells B2 to D2: Worksheets("Sheet1"), Range("B2:D4, F3:G6").Rows(1). Interior. Color = vbRed. Omitting the object qualifier will default to active sheet - following will apply color to row one of the ActiveSheet: Rows(1).Interior.Color = vbRed. To refer to a range as offset from a specified range, use the Range. Offset Property. Syntax: RangeObject Offset(RowOffset, ColumnOffset). Both arguments are optional to specify. The RowOffset argument specifies the number of rows by which the specified range is offset - negative values indicating upward offset and positive values indicating downward offset, with default value being 0. The ColumnOffset argument specifies the number of columns by which the specified range is offset - negative values indicating left offset and positive values indicating right offset, with default value being 0. Examples: Range("C5").Offset(1, 2) offsets 1 row & 2 columns and refers to Range E6, Range("C5:D7").Offset(1, -2) offsets 1 row downward & 2 columns to the left and refers to Range (A6:B8). Accessing a worksheet range, with vba code:- Referencing a single cell: object will assume the Value property, as shown below): Worksheets("Sheet”).Range("AT"). Value = 10 Worksheets("Sheet1").Range("A1") = 10 Enter the value of 10 in range C? of the active worksheet - using Cells(row. column) where row is the row index and column is the column index: ‘ActiveSheet. Cells(2, 3). Value 0 Referencing a range of cells: Enter the value 10 in the cells A1, A2, A3, B1, B2 & B3 (wherein the cells refer to the upperleft comer & lowe! right comer of the range) of the active sheet: ActiveSheet. Range("A1:B3"). Value = 10 ActiveSheet.Range("A1", "B3"). Value = 10 ActiveSheet.Range(Cells(1, 1), Cells(3, 2)) = 10 Enter the value 10 in the cells A1 & B3 of worksheet named Workshoets("Sheet"). Range("A1,B3"). Value = 10 he or Sl 7 of "Sheet" ‘Active Workbook. Worksheets ("Sheet3").Range("B2:03,H7").Interior.Color = vbRed Enter the value 10 in the Named Range "Score" of the active worksheet, viz, you can name the Range("B2:B3" as "Score" to insert 10 in the cells B2 & B3: ‘Range("Score"), Value = 10 ActiveSheet.Range("Score"). Value = 10 Select all the cells of the active worksheet ‘ActiveSheet. Cells, Select Cells, Select Set the font to "Times Now Roman" & the font size to 11, forall the calls of the active worksheet in the active ‘workbook: ‘ActiveWorkbook. ActiveSheet. Cells. Font. Name = "Times New Roman" ‘ActiveSheet. Cells. Font. Size = 11 Cells. Font. Size = 11 Sheet Referencing Row(s) or Column(s): Select all the Rows of active worksheet: ‘ActiveSheet. Rows. Select Enter the value 10 in the Row number 2 (ie. every cell in second row). of worksheet named "Sheet!" Worksheets("Sheett"). Rows (2). Value = 10 Select all the Columns of the active worksheet: ‘ActiveSheet. Columns. Select Columns. Select Enter the value 10 in the Column number 3 (ie. every cell in column C), of the active worksheet ActiveSheet. Columns(3). Value = 10 Columns("C"). Value = 10 Enter the value 10 in Column numbers 1, 2 & 3 (le. every cell in columns A to C), of worksheet named Worksheets("Sheet"). Columns(“A:C"). Value = 10 Relative Referencing: Inserts the value 10 in Range C5 - reference starts from upper-left comer of the defined Range: ‘Range("C5:E8").Range("A1") = 10 Inserts the value 10 in Range Dé - reference starts from upper-left comer of the defined Range: ‘Range("C5:E6"). Range("B2") = 10 Inserts the value 10 in Range E6 - offsets 1 row & 2 columns, using the Offset property: Range("C5").Offset(1, 2) = 10 Inserts the value 10 in Range("F7:H10") - offsets 2 rows & 3 columns, using the Offset propert ‘Range("C5:E8"), Offset(2, 3) = 10 Example 1 - Using Range, Cells, Columns & Rows property - refer Image 1: Wa ec ip eve onl scl ral Image 1 ‘Sub CellsColumnsRowsProperty() ‘using Range, Cells, Columns & Rows property - refer Image 1 Dim ws As Worksheet Dim mg As Range Dim r As Integer, c As Integer, n As Integer, i As Integer, j As Integer ‘set worksheet: Set ws = Worksheets("Sheet") ‘activate worksheet: ws activate ‘enter numbers starting from 1 in each row, for a5 row & 5 column range (A1:E5): Forr=1T05 n=1 Fore =1To5 Calls(r, ¢).Value pened Next ¢ Next r ‘set range to A1:E5, wherein the numbers have been entered as above: Set mg = Range(Cells(t, 1), Cells(6, 5)) ‘set background color of each even number column to yellow and of each odd number column to green: Fori=1T05 Ifi Mod 2 = 0 Then mg.Columns(i).Interior.Color = vbYellow Else mg.Columns().Interior.Color = vbGreen End If Next i ‘set font color to red and set font to bold for of even number rows: Forj=1T05 fj Mod 2 = 0 Then mg.Rows()).Font.Bold = True mg-Rows()). Font. Color = vbRed End if Next j ‘set font for all cells of the range to italics: mg.Cells.Font. Italic End Sub To retum the number of the first row in a range, use the Range. Row Property. If the specified range contains multiple areas, this property will retum the number of the first row in the first area (Areas property has been explained in detail later in this section). Syntax: RangeObject Row. To return the number of the first column in a range, use the Range.Column Property. If the specified range contains multiple areas, this property will retum the number of the first column in the first area. Syntax: RangeObject. Column. Examples: Get the number of the first row in the specified range - retums 4: ‘MsgBox ActiveSheet. Range("B4"). Row ‘MsgBox Worksheets("Sheet 1").Range("B4:07"). Row Get the number of the first column in the specified range - retums 2. ‘MsgBox ActiveSheet. Range("B4:D7"). Column the number of the last row in the specified range - ratums 7: Explanation: Range("B4:07").Rows.Count retums 4 (the number of rows in the range). Range("B4:D7"), Rows (Range(’B4:D7")-Rows. Count) or Range("B4:D7").Rows(4), retus the last row in the specified range. ‘MsgBox Range('B4:07").Rows(Range("B4:D7").Rows. Count). Row Example 2: Using Row Property, Column Property & Rows Property, determine row number & column number, and alternate rows - refer Image 2. cals) of] 5/0] 4 Alecks Image 2 ‘Sub RowColumnProperty() "Using Row Property, Column Property & Rows Property, determine row number & column number, and altemate rows - refer Image 2, Dim mg As Range, cell As Range Dim i As Integer Set mg = Worksheets("Sheel1").Range(’B4:D7") ‘enter its row number & column number within each call in the specified range: For Each cell Inmg ‘cell. Value = cell. Row & ", Next & cell,Column ‘set background color of each alternate row of the specified range. Fori = 1 To mg.Rows.count ITi Mod 2= 1 Then mg-Rows()).Interior Color = vbGreen Else mg.Rows(i).Interior.Color = vbYellow End if Next End Sub Also refer to Example 23 in the section "Referencing Cells & Ranges - 2" (index.php? ‘option=com_content&view=article&id=187:excel-vba-referring-to-ranges-part-2&catid=79<emid=475HExample 23), of using the End & Row properties to determine the last used row or column with data. ‘You can get a Range reference in vba language by using the Range. Address Property, which retums the address of a Range as a string value. This property Is read-only. Examples of using the Address Property Retums $882 ‘MsgBox Range("B2"). Address Retums $8: MsgBox Range(*B2,03").Address Retums $A81:$B: 33,808 Dim strRng As String Range("A1:82,C3,D4").Select string = Selection Address MsgBox strRng Retums $82: ‘MsgBox Rango("B2").Address(RowAbsolute:=False) Retums BS2 ‘MsgBox Rango("B2"), Address(ColumnAbsolut Retums R202: ‘MsgBox Range("B2").Address(ReferenceStyle:=xiR1C1) Includes the worksheet (active sheet - "Sheet1") & workbook ("Book xism") name, and retums [Book 1 xlsm)Sheet 1!SB$2: ‘MsgBox Range(*B2"). Address (External rue) Retums RI1|C[-1] - Range("B2") is 4 row and -1 columns relative to RangeC(C1"): ‘MsgBox Range("B2"). Address (RowAbsolute:=False, ColumnAbsolute:=False, ReferenceStyl RelativeTo:=Range("C1")) ‘MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolut RelativeTo:=Range("C1")) Activate & Select Cells; the ActiveCell & Selection ‘The Select method (of the Range object) is used to select a cell or a range of cells in a worksheet - Syntax: RangeObject. Select. Ensure that the worksheet wherein the Select method is applied to select cells, is the active sheet. The ActiveCell Property (of the Application object) retums a single active cell (Range object) in the active worksheet. Remember that the ActiveCell property will not work if the active sheet is not a worksheet. When a cells) is selected in the active window, the Selection property (of the Application object) returns a Range object representing all cells which are currently selected in the active worksheet. A Selection may consist of a single cell or a range of multiple cells, but there will only be one active cell within it, which is retumed by using the ActiveCell property. When only a single cell is selected, the ActiveCell property relums this cell. On selecting multiple cells using the Select method, the first referenced cell becomes the active cell, and thereafter you can change the active cell using the Activate method. Both the ActiveCell Property & the Selection property are read-only, and not specifying the Application object qualifier viz. Application. ActiveCell or ActiveCell, Application. Selection or Selection, will have the same effect. To activate a single cell within the current selection, use the Activate Method (of the Range object) - ‘Syntax: RangeObject Activate, and this activated cell is retumed by using the ActiveCell property. We have discussed above that a Selection may consist of a single cell or a range of multiple cells, whereas there can be only one active cell within the Selection. When you activate a cell outside the current selection, the activated cell becomes the only selected cell. You can also use the Activate method to specify a range of multiple cells, but in effect only a single cell wil be activated, and this activated cell wil be the topeft comer cell of the range specified in the method. If this top-left cell lies within the selection, the current selection will not change, but if this top-left cell lies ‘outside the selection, then the specified range in the Activate method becomes the new selection. ‘See below codes which illustrate the concepts of ActiveCell and Selection. Selection containing a range of cells, and the active cell ‘selects range C1:F5: Range("C1:F5").Select ‘retums C1, the first referenced cell, as the active cel! MsgBox ActiveCell Address ection containing a range of cells, and the active colt ‘selects range C1:F5: Range("F5:C1").Select ‘retums C1, the first referenced cell, as the active col! MsgBox ActiveCell Address Selection containing a range of cells, and the active cell ‘selects range C1:F5: Range("C5:F1").Select ‘retums C1, the first referenced cell, as the active cell MsgBox ActiveCell. Address Activate a cell within the current selection: ‘selects range B6:F10: Range("B6:F10").Select ‘retums B6, the first referenced cell, as the active cel: MsgBox ActiveCell. Address ‘selection remains same - range B6:F10, but the active cell is now C8: Range("C8") Activate MsgBox ActiveCell. Address Activ H ion: ‘selects range B6:F10: Range("B6:F10").Select ‘retums B6, the first referenced coll, as the active coll: MsgBox ActiveCell. Address ‘both the selection and the active cell is now A2: Range("A2") Activate MsgBox ActiveCell, Address Select a cell within the current selection: ‘selects range B6:F10: Range("B6:F10").Select ‘retums B6, the first referenced cell, as the active cel: MsgBox ActiveCell, Address ‘both the selection and the active cell is now C8: Range("C8"), Select MsgBox ActiveCell Address Image 3b ‘selects range B6:F10-- refer Image 3a: Range("B6:F 10") Select Yetums B6, the first referenced cell, as the active cell. MsgBox ActiveCell.Addross ‘selection remains same - range B6:F10, but the active cell is now C8 - refer Image 3b: Range(*C8:G12") Activate MsgBox ActiveCall Address Image 3c ‘selects range B6:F10 - refer Image 3a Range("B6:F10").Select ‘retums 6, the first referenced cell, as the active coll: MsgBox ActiveCell. Address ‘selection range changes to range B1:F8, and the active cell is now 81 - refer Image 3c: Range("B1:F8") Activate MsgBox ActiveCell. Address Using the Application Selection Property retums the selected object wherein the selection determines the retumed ‘object type. Where the selection is a range of cells, this property retums a Range object, and this Selection - which is, a Range object - can comprise of a single cell, or multiple cells or multiple non-contiguous ranges. And as mentioned above, the Select method (of the Range object) is used to select a cell or a range of cells in a worksheet. Therefore, after selecting a range, you can perform actions on the selection of calls by using the Selection object. See below ilustration. Sub SelectionObject() ‘select cells in the active sheet using the Range.Select method: Range("A1:B3,D6") Select ‘perform action (set interior color of cells to red) on the Selection, which is a Range object: Selection, Interior.Color = vbRed End Sub Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method Use the Range.EntireRow Property to retum an entire row or rows within which the specific range is contained. Using this property retums a Range object referring to the entire row(s). Syntax: RangeObject EntireRow. Use the Range.EntireColumn Property to return an entire column or columns within which the specific range is contained. Using this property retums a Range object referring to the entire column(s). Syntax: RangeObject Entirecolumn. Examples of using the EntireRow & EntireColumn Properties lects row no. 2: Range("A2").EntireRow.Select Selects row nos. 2. 3 & 4: Range("A2:C4").EntireRow. Select Cells(3, 4).EntireRow.Cells(1, 1).Value = 3 Selects column A: Range("A2").EntireColumn.Select Selects columns A to C: Range("A2:C4").EntireColumn. Select Enters value 4 in range D1 ie. in the first call of column no. 4: olls(3, 4).EntireColurnn, Cells(1, 1). Value = 4 Use the Range.Insert Method to insert a cell or a range of cells in a worksheet. Syntax: RangeObject.Insort(Shift, CopyOrigin). Both arguments are optional to specify. When you insert cell(s) the other cells are shifted to make way, and you can set a value for the Shift argument to determine the direction in which the other cells are shifted - specifying xiShiftDown (value -4121) will shift the cells down, and xIShiftToRight (value -4161) shifts the cells to the fight. Omitting this argument will decide the shift direction based on the shape of the range. Specifying xiFormatFromLeftOrAbove (value 0) for the CopyOrigin argument will copy the format for inserted call(s) from the above cells or cells to the left, and specifying xiFormatFromRightOrBelow (value 1) will copy format from the below cells or cells to the right. Illustrating Range.Insert Method - for start data refer Image 4a: Image 4b Shifts cells down and copies formatting of inserted cell from above cell - refer image 4b: Range("B2’).Insert Image 4c Shifts cells to the right and copies formatting of inserted cells from cells to the left - refer imane do: Range("B2:C4").Insert Image 4e Shifts cells down and copies formatting of inserted cells from below calls - refer image de. Range("B2:03"). nsert Copy Origin:=xiFormatFromRightOrBelow Image 4f Shifts cells to the right and copies formatting of inserted cells from cells to the left - refer image 4f: Range("B2:03").Insert shift:=xIShiftToRight Image 4g hifts cells to the right and copies formatting of in Is from calls to the right - refer image 4 Range("B2:03").Insert shift:=xIShiffToRight, CopyOrigin:=xiFormatFromRightOrBelow Image 4h Inserts 2 rows -row no 2 & 3- and copies formatting of inserted rows from above cells - refer image 4h: Range("B2:03").EntireRow. Insert Below are some illustrations of inserting entire row(s) or column(s) dynamically in a worksheet. Example 3: Insert row or column - specify the row / column to insert. Sub InsertRowColumn() ‘Insert row or column - specify the row / column to insert Dim ws As Worksheet Set ws = Worksheets("Sheet1") "NOTE: each of the below codes need to be run individually. ‘specify the exact row number to insert - insert a row as row no 12: ws.Rows(12).Insert ‘specify the range below which to insert a row - insert a row below range C3 ie. as row no 4, ws.Range("C3").EntireRow.Offset(1, 0).Insert ‘specify the exact column number to insert - insert a column as column no 4: ws.Columns(4) Insert ‘specify the range to the right of which to insert a column - insert a column to the right of range C3 ie. as column no 4. ws. Range(*C3"),EntireColumn. Offset(0, 1).Insert End Sub Example 4: Insert row(s) after a spe: Sub InsertRow1() ‘insert row(s) after a specified value is found: Dim ws As Worksheet Dim mngFind As Range, mgSearch As Range, mgLastCell As Range Dim IFindRow As Long Set ws = Worksheets("Sheet 1") ‘find a value after which to insert a row: Set mgSearch = ws.Range(‘A1:E100") ‘begin search AFTER the last cell in search range (this will start serach from the first cell In search range): Sel mgLastCell = mgSearch.Cells(mgSearch.Cells. count) ‘Set mgFind = mgSearch.Find(What:="ExcelVBA", After:=rgLastCell, LookIn:=xlValues, lookat:=xiWhole) ‘exit procedure if value not found: I Not mgFind Is Nothing Then IFindRow = mgFind.Row MsgBox IFindRow Else MsgBox "Value not found!” Exit Sub End If "NOTE: each of the below codes need to be run individually. ‘f-value found is in row no 12, one row will be inserted below as row no 13: ws.Cells(IFindRow + 1, 1).EntireRow.Insert ‘if value found is in row no 12, one row will be inserted 3 rows below (as row no 15): ws.Cells(IFindRow + 3, 1),EntireRow.nsert ‘f value found is in row no 12, one row will be inserted 3 rows below (as row no 15) ws.Cells(IFindRow, 1).Offset(3).EntireRow.Insert ‘if value found is in row no 12, 3 rows will be inserted above (as row nos 12, 13 & 14) and the value found row 12 will be pushed down to row 15: ws.Cells(IFindRow, 1) EntieRow Resize(3). Insert ‘alternate: ws. Rango(Cells(FindRow, 1), Cells(FindRow + 2, 1))-EntireRow.Insert ‘altemate: ws, Rows(lFindRow & *" & IFinRow + 2) EntireRow.Insert Shift:=xIDown ‘f value found is in row no 12, 3 rows will be inserted below (as row nos 13, 14 & 15) and the value found row 12 will remain at the same position: ws.Cells(IFindRow + 1, 1).EntireRow.Resize(3).Insert ‘altemate: ws. Range(ws.Cells(|FindRow + 1, 1), ws.Cells(IFindRow + 3, 1)),EntireRow. Insert ‘f value found is in row no 12, 3 rows will be inserted after row no 13 (as row nos 14, 1 & 16) and existing rows 12 & 13 will remain at the same position ws.Cells(IFindRow + 2, 1).EntireRow Resize(3).Insert End Sub Example 5: Insert a row, n rows above the last used row. Sub InsertRow2() ‘insert a row, n rows above the last used row Dim ws As Worksheet Dim IRowsC As Long Set ws = Worksheets("Sheet: ) ‘determine the last used row in a column (column A): IRowsC = ws.Cells(Rows. count, "A")-End(xlUp). Row MsgBox IRawsC. ‘set n to the no of rows above the last used row: n=5 ‘check if there are enough rows before the last used row, else you will get an error: If Rows >= n Then ‘insert a row, n rows above the last used row - if last used row is no 5 before insertion, then insert as Tow no 1 and the last used row will become no 6 (similarly, if last used row is 27, then insert as row no 23) ws. Rows((RowsC).Offset(-n + 1, 0)-EntireRow. Insert Else MsgBox "Not enough rows before the last used row!" End if End Sub Example 6: Insert a row each time the searched value is found in a range. For live code of this example, click to download excel file {http://globaliconnect.com/excel/downloadfiles/VBA/RangeReferlVBAInsertRowAfterValueFound.xism) Sub InsertRow3() ‘search value in a range and insert a row each time the value is found. ‘you can set the search range with the variable mgSearch in below code - the code will look within this range to find the value below which row is to be inserted. Dim ws As Worksheet Dim mgFind As Range, mgSearch As Range, mgLastCell As Range Dim strAddress As String Set ws = Worksheets("Sheett") ‘set search range: ‘Set mgSearch = ws.Range(‘A1:K100") MsgBox "Searching for 'ExcelVBA' within range: "begin search AFTER the last cell in search range Sot mgLastCell = mgSearch.Calls(mgSearch.Calls. count) & mgSearch.Address, ‘find value in specified range, starting search AFTER the last cell in search range: ‘Set mgFind = mgSearch.Find(What:="ExcelVBA", After:=mgLastCell, Lookin:=xValues, lookat:=xiWhole) If mgFind Is Nothing Then MsgBox "Value not found!" Exit Sub Else ‘save cell address of first value found: strAddress = mgFind. Address Do ‘find next occurrence of value: Set mgFind = mgSearch.FindNext(After:=mgFind) ‘insert row below when value is found (if value is found twice in a row, then 2 rows will be inserted): mgFind. Offset(1).EntireRow.Insert ‘ioop till reaching the first value found range: Loop While mgFind. Address <> strAddress. End If End Sub Example 7: Insert rows (user-defined number) within consecutive values found in a column - refer Images 5a & Sb. For live code of this example, click to download excel file. {(http://globaliconnect.com/excel/downloadfiles/VBA/RangeRefer/VBAInsertRowWithinConsecutiveValuesinColumn.xism) Ta B c D E F US States |Population| Capital |Location| Area Code| Per Capita [Alabama ‘Alaska (California 1 2 3 4 2 6 7 Fonda 8 fichigan [BiiNevaca 30 11 [Ohio 12 [Texas Image 5a ins 8 c D E F Us States |Population| Capital |Location| Area Code| Per Capita (Alabama ‘Alaska California 1 2 3 4 5 6 iz 8 Torida i Michigan 12 B Nevada 14 (Ohio 16 a7] Texas Image 5 Sub InsortRow4() ‘insert rows (user-defined number) wherever 2 consecutive values are found in a column. ‘set column number in which 2 consecutive values are checked to insert rows, using the variable ICellColumn in below code. ‘set row number from where to start searching consecutive values, using the variable ICellRow in below code. ‘refer Image Sa which shows raw data, and Image 5b after this procedure is executed - a single row (IRowsinsert value entered as 1 in input box) is inserted where consecutive values appear in column 1 Dim ws As Worksheet Dim ILastUsedRow As Long, IRawsinsert As Long, ICellRow As Long, ICellColumn As Long Dim mg As Range Set ws = Worksheets("Sheet1") ws.Activate ‘set column number in which 2 consecutive values are checked to insert rows: ICeliColumn ‘set row number from where to start searching consecutive values: ICellRow = 4 ‘determine the last used row in the column (column no. !CellColumn): ILastUsedRow = Cells(Rows.count, ICeliColumn).End(xlUp) Row ‘enter number of rows to insert between 2 consecutive values: IRowsInsert = InputBox("Enter number of rows to insert”) If Rowsinsert < 1 Then MsgBox "Error - please enter a value equal to or greater than 1” Exit Sub End If MsgBox "This code will insert " & IRowsinsert & " rows, wherever consecutive values are found in column number" & ICellColumn & ", starting search from row number " & ICellRow ‘loop tll the row number equals the last used row (ie. loop right til the end value in the column): Do While IGellRow < ILastUsedRow ‘Set mg = Colls(ICellRow, ICellColumn) {in case of 2 consecutive values: It mg <>" And mg.Offset(1, 0) <>" Then ‘enter the user-defined number of rows: Range(mg.Offset(1, 0), mg.Offset(|RowsInsert, 0)). EntireRow.Insert ICellRow = ICelRow + IRowsinsert + 1 ‘determine the last used row - it is dynamic and changes on insertion of rows: ILastUsedRow = Cells(Rows.count, ICellColumn).End(xlUp). Row ‘alternate method to determine the last used row, when number of rows inserted is fixed - this is faster than using End(x/Up): ‘iLastUsedRow = ILastUsedRow + IRowsinsert + 1 "MsgBox ILastUsedRow Else ICellRow = ICelRow + 1 End If Loop End Sub Next > (Jexcel/index.php?option=com_content&view-article&id=288:referencing-cells-e-ranges-in-vba- 28 catid=9281temid=524) On Air with AIB . Watch the Latest Episode of AIB's New Show, Now Streaming on hotstar! © 2015 Globaliconnect.com (http://www. globaliconnect.com/excel_new/) All Right Reserved Back to Top

You might also like