在Excel VBA中多次引用单元格的较短方法
我使用下面的代码块来设置一些初始值。我发现我自己经常使用这个结构,我想知道是否有更简洁的东西在Excel VBA中多次引用单元格的较短方法,vba,excel,excel-2010,Vba,Excel,Excel 2010,我使用下面的代码块来设置一些初始值。我发现我自己经常使用这个结构,我想知道是否有更简洁的东西 Sheets(AppTab).Select Cells(StartingRow, Range("AppTransEffDate").Column).Value = FirstPymtDueDate Cells(StartingRow, Range("AppTransAmt").Column).Value = RegularPymt Cells(StartingRow, Range("AppActionC
Sheets(AppTab).Select
Cells(StartingRow, Range("AppTransEffDate").Column).Value = FirstPymtDueDate
Cells(StartingRow, Range("AppTransAmt").Column).Value = RegularPymt
Cells(StartingRow, Range("AppActionCode").Column).Value = SchPymtDueActionCode
Cells(StartingRow, Range("AppDescr").Column).Value = TransDescr
如果重要的话,每个范围都有一列宽。使用一个或多个语句
with Sheets(AppTab)
.Cells(StartingRow, .Range("AppTransEffDate").Column) = FirstPymtDueDate
.Cells(StartingRow, .Range("AppTransAmt").Column) = RegularPymt
.Cells(StartingRow, .Range("AppActionCode").Column) = SchPymtDueActionCode
.Cells(StartingRow, .Range("AppDescr").Column) = TransDescr
end with
'alternate
with Sheets(AppTab)
with .rows(StartingRow)
.Cells(1, .Range("AppTransEffDate").Column) = FirstPymtDueDate
.Cells(1, .Range("AppTransAmt").Column) = RegularPymt
.Cells(1, .Range("AppActionCode").Column) = SchPymtDueActionCode
.Cells(1, .Range("AppDescr").Column) = TransDescr
end with
end with
我不认为第二个是。。。。在本例中,End With将显示与第一个相同的改进,但隔离引用的单元格更有效,并避免重复调用以查找父级
始终明确引用父工作表被广泛认为是“最佳实践”,避免使用.Select和.Activate。我会使用枚举来引用列号。枚举位于代码模块的顶部。列表中的下一个枚举是上一个枚举的增量1。枚举列的最大优点是当您需要对列重新排序时;您只需更新枚举,代码就会像以前一样运行。枚举也适用于intellisense
我通常的方法是设置行范围的第一个单元格,然后使用范围。\u Default属性 但是,我不使用命名范围,而是像Thomas Inzina的答案中那样使用Enum 如果命名范围从第1行开始,那么这可能会起作用
Range("AppTransEffDate")(StartingRow) = FirstPymtDueDate
或
或者Intersect也可能起作用:
Set areas = Sheets(AppTab).Range("(AppTransEffDate,AppTransAmt,AppActionCode,AppDescr) " & StartingRow & ":" & StartingRow).Areas
areas(1) = FirstPymtDueDate
areas(2) = RegularPymt
areas(3) = SchPymtDueActionCode
areas(4) = TransDescr
有没有办法缩短.CellsStartingRow、.RangeAppTransaffDate.Column=FirstPymtDueDate我需要保持StartingRow作为变量,因为它会发生变化我不知道AppTransaffDate、AppTransaft、AppActionCode和AppDescr在哪里或指什么,所以不,我不能提出任何建议。这些是范围。每一个基本上都只是F、H等列的一长串。我已经开始使用这个方法,代码可以工作,但Intellisense不显示枚举,但在其他方面可以工作。还有什么我需要做的,使它拿起枚举?是否在我键入:StartingRow,cn[此处智能感知]后出现?是,键入'cn',然后按住[ctrl]+[空格键]。
Range("AppTransEffDate")(StartingRow) = FirstPymtDueDate
Set areas = Sheets(AppTab).Range("AppTransEffDate,AppTransAmt,AppActionCode,AppDescr").Areas
areas(1)(StartingRow) = FirstPymtDueDate
areas(2)(StartingRow) = RegularPymt
areas(3)(StartingRow) = SchPymtDueActionCode
areas(4)(StartingRow) = TransDescr
Set areas = Sheets(AppTab).Range("(AppTransEffDate,AppTransAmt,AppActionCode,AppDescr) " & StartingRow & ":" & StartingRow).Areas
areas(1) = FirstPymtDueDate
areas(2) = RegularPymt
areas(3) = SchPymtDueActionCode
areas(4) = TransDescr