0

In a worksheet, there are two named ranges, each of which only contains a row, e.g. Range1 = Range("B5:H5") and Range2 = Range("B9:H9"). My question is: how can I reference a cell in Range1, say C5, and a cell in Range2, say C9 in VBA so that I can do something with the values in these two cells? The VBA should only run for the active column. Thank you in advance.

Leon
  • 33
  • 5

4 Answers4

2

Maybe you should see this link.

How to avoid using Select in Excel VBA macros

As Siddarth stated,

Two Main reasons why .Select/.Activate/Selection/Activecell/Activesheet/Activeworkbook etc... should be avoided

It slows down your code.
It is usually the main cause of runtime errors.

How do we avoid it?

1) Directly work with the relevant objects

Consider this code

Sheets("Sheet1").Activate
Range("A1").Select
Selection.Value = "Blah"
Selection.NumberFormat = "@"

This code can also be written as

With Sheets("Sheet1").Range("A1")
    .Value = "Blah"
    .NumberFormat = "@"
End With

2) If required declare your variables. The same code above can be written as

Dim ws as worksheet

Set ws = Sheets("Sheet1")

With ws.Range("A1")
    .Value = "Blah"
    .NumberFormat = "@"
End With
ASH
  • 20,759
  • 19
  • 87
  • 200
0

Use can

Range1.offset() 

method to refer adjacent cell

You can refer here for detail .

The KNVB
  • 3,588
  • 3
  • 29
  • 54
  • Thanks, KNVB. I would like to use the range names rather than Offset in case a user changes the spreadsheet layout. I can use: variable1 = ActiveSheet.Columns(ActiveCell.Column).Row(5) and variable2 = ActiveSheet.Columns(ActiveCell.Column).Row(9), but this does not use the named ranges. – Leon Jun 28 '17 at 02:26
0

Would this work?

Range("Range1").Cells(1, 1).Select     'Selects Range("B5") - first cell in Range1
Range("Range1").Cells(1, "A").Select   'Also selects first cell in the named range

'copies cell 2 (C9) from Range2 into cell 2 (C5) of Range1; .Cells(row, col)
Range("Range1").Cells(1, 2) = Range("Range2").Cells(1, 2)
paul bica
  • 10,557
  • 4
  • 23
  • 42
0

By using the Cells method, you can specify the appropriate row using Range1.Row (and Range2.Row), and the appropriate column using (if I understand you correctly) Selection.Column.

So perhaps something like:

Dim Range1 As Range
Dim Range2 As Range
Set Range1 = Range("B5:H5")
Set Range2 = Range("B9:H9")

'Display the value in row 5 for the current column
MsgBox Cells(Range1.Row, Selection.Column).Value
'Display the value in row 9 for the current column
MsgBox Cells(Range2.Row, Selection.Column).Value

'Change row 9 to be the value from row 5
Cells(Range2.Row, Selection.Column).Value = Cells(Range1.Row, Selection.Column).Value

'Display the updated value in row 9 for the current column
MsgBox Cells(Range2.Row, Selection.Column).Value
YowE3K
  • 23,852
  • 7
  • 26
  • 40