Question

I have the following formula Range("D3" , "D" & Total_Rows) = "=sum(A1:A10)" If I insert a column before D, this formula now is put in the wrong column. I have been told to use a named range for column D, but with this type of code, I don't see how I could incorporate the named range because in one instance I need it to refer to a single cell and in the other I need it to refer to a column.

Was it helpful?

Solution

I don't see how I could incorporate the named range because in one instance I need it to refer to a single cell and in the other I need it to refer to a column.

Well you could try working with the Name's range properties, and then you can use ordinary range methods like .Resize or .Offset, etc.

Sub Test()

'Assume there is a named range in the worksheet 
Dim nm As Name
Dim rngName As Range
Dim rngCell As Range
Dim rngColumn As Range


Set nm = ActiveSheet.Names(1)

Set rngName = Range(nm)
    MsgBox "myName address: " & rngName.Address
Set rngCell = Range(nm).Resize(1, 1)
    MsgBox "the first cell in myRange is " & rngCell.Address
Set rngCell = Range(nm).Resize(1, 1).Offset(3)
    MsgBox "the third cell in myRange is " & rngCell.Address
Set rngColumn = Range(nm).EntireColumn
    MsgBox "the column of myRange is " & rngColumn.Address

'Now insert a column in front of D

rngName.Insert

'Then view the addresses again, see that they have changed

Set rngName = Range(nm)
    MsgBox "myName address: " & rngName.Address
Set rngCell = Range(nm).Resize(1, 1)
    MsgBox "the first cell in myRange is " & rngCell.Address
Set rngCell = Range(nm).Resize(1, 1).Offset(3)
    MsgBox "the third cell in myRange is " & rngCell.Address
Set rngColumn = Range(nm).EntireColumn
    MsgBox "the column of myRange is " & rngColumn.Address


End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top