简体   繁体   English

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

[英]How to rename range using VBA in excel 2007

I've 8+ yes professional programming experience in PHP and Java but none in VBA. 我有8年以上的PHP和Java专业编程经验,但没有VBA的经验。 Learning it right now. 立即学习。

I'm trying to make a Home budget sheet (Just for VBA learning purpose). 我正在尝试制作房屋预算表(仅出于VBA学习目的)。 For that, I'd done following 为此,我已经完成了

* 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.

I wrote following code for that (Recorded testmacro to check how to name a range) 我为此编写了以下代码(已记录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

While selecting the range, I got following error 选择范围时,出现以下错误

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

I'm unable to understand what that error mean and why I'm getting that by just adding worksheet name. 我无法理解该错误的含义,以及为什么我只能通过添加工作表名称来获取该错误。

Again, What does following line mean? 同样,以下几行是什么意思? What is happening there? 那里发生了什么事? I could not understand meaning of R2C1:R3C2. 我无法理解R2C1:R3C2的含义。 This values came from recorded macro when I named A2:A3 cells as 'categories' 当我将A2:A3单元命名为“类别”时,此值来自录制的宏

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

You do not need to select the range Range("A2:A3").Select . 您无需选择范围Range("A2:A3").Select The "=CatAcc!R2C1:R3C1" in the next line is automatically taking care of it. 下一行中的"=CatAcc!R2C1:R3C1"会自动进行处理。

Explanation 说明

"=CatAcc!R2C1:R3C1" “= CatAcc R2C1:R3C1”

  1. CatAcc is the Sheet where the range is CatAcc是工作表的范围
  2. R2C1 means Row 2 Col 1 which is nothing but A2 R2C1表示第2行第1列,不过是A2
  3. Similarly R3C1 is Row 3 Col 1 which is nothing but A3 同样,R3C1是第3行第1行,不过是A3

So the above can also be written as 所以上面也可以写成

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM