VBA代码和命名范围中的相对范围

时间:2014-04-24 16:09:37

标签: excel vba excel-vba named-ranges

我有以下公式Range("D3" , "D" & Total_Rows) = "=sum(A1:A10)"如果我在D之前插入一列,此公式现在放在错误的列中。我被告知要为D列使用命名范围,但是对于这种类型的代码,我看不出如何合并命名范围,因为在一个实例中我需要它来引用单个单元格而在另一个实例中我需要它来引用一列。

1 个答案:

答案 0 :(得分:0)

  

我没有看到如何合并命名范围,因为在一个实例中我需要它来引用单个单元格而在另一个实例中我需要它来引用一个列。

您可以尝试使用Name的范围属性,然后您可以使用普通范围方法,例如.Resize.Offset等。

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