PDA

View Full Version : [SOLVED:] VBA Excel: Ranges



Malak
03-29-2020, 07:23 AM
Hello,
is it possible to wirte the three lines in one line without listing all the offsets, but using one range to describe the three offsets?
Basically I am looking for a way to offset a range of cells like cells(-2, -2), cells(-1, -2)cells(-0, -2) from a base cell.
Malak




Sub RangeOffset()
Dim strBaseCell As String
strBaseCell = "D10"
Cells.Interior.ColorIndex = xlColorIndexNone
Range(strBaseCell).Offset(-2, -2).Cells.Interior.ColorIndex = 41
Range(strBaseCell).Offset(-1, -2).Cells.Interior.ColorIndex = 41
Range(strBaseCell).Offset(0, -2).Cells.Interior.ColorIndex = 41
End Sub

rlv
03-29-2020, 07:59 AM
Perhaps something like this.

Sub RangeOffset()
Dim strBaseCell As String
strBaseCell = "D10"
Cells.Interior.ColorIndex = xlColorIndexNone
Range(strBaseCell).Offset(-2, -2).Resize(3).Interior.ColorIndex = 41
End Sub

jolivanes
03-29-2020, 09:18 AM
Or use the "With ..... End With"

With Range("D10").Offset(-2, -2).Resize(3)
.Interior.ColorIndex = xlColorIndexNone
.Interior.ColorIndex = 41
End With

SamT
03-29-2020, 09:46 AM
Building on the previous two posts...
Option Explicit

Const myBlue as Variant = 41
Const myRed As Variant = 3

Sub SamT_VBAX_TestBlue()
Cells.Interior.ColorIndex = xlColorIndexNone
ColorMe Range("D10"), myBlue
End Sub

Sub SamT_VBAX_TestRed()
Cells.Interior.ColorIndex = xlColorIndexNone
ColorMe Range("D10"), myRed
End Sub


Public Function ColorMe(Rng2Clr As Range, MYColor as Variant)
Rng2Clr.Offset(-2, -2).Resize(3).Interior.ColorIndex = MYColor
End Function

Malak
03-30-2020, 06:09 AM
Thank you everyone for your help! :)