我在 PHP 和 Java 方面有 8 年以上的专业编程经验,但在 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.
我为此编写了以下代码(记录 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"