How To Select A Range Of Cells In Excel Vba

How to select a range of cells in Excel VBA

In Excel VBA, you can use the Range object to select a range of cells. The Range object represents one or more cells on a worksheet and allows you to perform various operations on the cells. Here’s how you can select a range of cells in Excel VBA:

1. Selecting a single cell:


    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")  ' Replace "Sheet1" with your sheet name
    ws.Range("A1").Select
  

This code selects cell A1 on “Sheet1”. You can change the range (e.g., “B2”, “C3”) based on your needs.

2. Selecting a range of cells:


    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")  ' Replace "Sheet1" with your sheet name
    ws.Range("A1:B5").Select
  

This code selects the range of cells from A1 to B5 on “Sheet1”. You can change the range (e.g., “C2:F10”, “D4:G7”) based on your needs.

3. Selecting multiple non-contiguous ranges:


    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")  ' Replace "Sheet1" with your sheet name
    ws.Range("A1:B5,C7:E10,G1:G10").Select
  

This code selects multiple non-contiguous ranges of cells on “Sheet1”. You can change the ranges based on your needs.

Once you have selected the range of cells, you can perform various operations on them, such as formatting, copying, pasting, etc. For example, to format the selected range with a border, you can use the following code:


    Selection.BorderAround ColorIndex:=1, Weight:=xlMedium
  

Note that the above examples assume that you have a worksheet named “Sheet1” in your workbook. You can replace “Sheet1” with the actual name of your worksheet.

Hope this helps! Let me know if you have any further questions.

Read more

Leave a comment