如何在excel 2007中使用VBA重命名范围

时间:2013-04-16 20:23:06

标签: excel vba excel-vba excel-2007

我有8+是PHP和Java的专业编程经验,但在VBA中没有。现在就学习。

我正在尝试制作一份家庭预算表(仅供VBA学习之用)。为此,我做了以下

* In new excel (2007) file, rename sheet 1 as 'Forms' And Sheet2 as 'CatAcc'
* In sheet 'CatAcc', I'm using (planning) column A for categories and B for Account
* Row 1 is heading (A1 = "Categories", B1="Account"
* Using forms sheet (cell C2) & VBA button, I want to add a new category,
  sort it alphabetically and then rename range to add newly added row.

我为此编写了以下代码(Recorded testmacro以检查如何命名范围)

Sub AddCat_Click()
    'Copy data as last row
    Worksheets("CatAcc").Cells(Rows.Count, "A").End(xlUp).Offset(1).Value = Worksheets("Forms").Cells(2, "C").Value

    'Find total Rows in categories
    Dim totalRows
    totalRows = Worksheets("CatAcc").Range("A2").End(xlDown).Row

    'Define Range
    Dim rng
    rng = "A2:A" & totalRows
    'MsgBox rng

    'Select the range - Getting error in following line.
    Worksheets("CatAcc").Range(rng).Select

    'Name the range
    ActiveWorkbook.Names.Add Name:="categories", RefersToR1C1:="=CatAcc!R2C1:R3C1"

    'Sort range alphabetically

    'Apply range as drop-down options
End Sub
Sub testmacro()
    Range("A2:A3").Select
    ActiveWorkbook.Names.Add Name:="categories", RefersToR1C1:= _
        "=CatAcc!R2C1:R3C1"
End Sub

选择范围时,我收到了以下错误

Run-time error '1004'
Select method of Range class failed

我无法理解该错误的含义以及为什么我只需添加工作表名称即可获得该错误。

再次,跟随线是什么意思?那里发生了什么?我无法理解R2C1:R3C2的含义。当我将A2:A3单元命名为“类别”

时,此值来自记录的宏
ActiveWorkbook.Names.Add Name:="categories", RefersToR1C1:="=CatAcc!R2C1:R3C1"

1 个答案:

答案 0 :(得分:1)

您无需选择范围Range("A2:A3").Select。下一行中的"=CatAcc!R2C1:R3C1"会自动处理它。

<强>解释

“= CatAcc R2C1:R3C1”

  1. CatAcc是范围
  2. 的工作表
  3. R2C1表示第2行第1列,它只是A2
  4. 类似地,R3C1是行3 Col 1,它只是A3
  5. 所以上面的内容也可以写成

    ActiveWorkbook.Names.Add NAME:="categories", RefersTo:="=CatAcc!$A$2:$A$3"