在工作表中,有两个命名范围,每个范围仅包含一行,例如范围1 =范围(“B5:H5”)和范围2 =范围(“B9:H9”)。我的问题是:如何引用Range1中的单元格,比如C5,以及Range2中的单元格,比如VBA中的C9,以便我可以对这两个单元格中的值做一些事情? VBA应仅针对活动列运行。先感谢您。
答案 0 :(得分:1)
也许你应该看到这个链接。
How to avoid using Select in Excel VBA macros
正如Siddarth所说,
两个主要原因。应该避免选择/。激活/选择/ Activecell / Activesheet / Activeworkbook等......
It slows down your code.
It is usually the main cause of runtime errors.
我们如何避免它?
1)直接使用相关对象
考虑这段代码
Sheets("Sheet1").Activate
Range("A1").Select
Selection.Value = "Blah"
Selection.NumberFormat = "@"
This code can also be written as
With Sheets("Sheet1").Range("A1")
.Value = "Blah"
.NumberFormat = "@"
End With
2)如果需要,声明你的变量。上面相同的代码可以写成
Dim ws as worksheet
Set ws = Sheets("Sheet1")
With ws.Range("A1")
.Value = "Blah"
.NumberFormat = "@"
End With
答案 1 :(得分:0)
答案 2 :(得分:0)
这会有用吗?
Range("Range1").Cells(1, 1).Select 'Selects Range("B5") - first cell in Range1
Range("Range1").Cells(1, "A").Select 'Also selects first cell in the named range
'copies cell 2 (C9) from Range2 into cell 2 (C5) of Range1; .Cells(row, col)
Range("Range1").Cells(1, 2) = Range("Range2").Cells(1, 2)
答案 3 :(得分:0)
使用Cells
方法,您可以使用Range1.Row
(和Range2.Row
)指定相应的行,并使用相应的列(如果我理解正确的话){{1} }。
或许类似于:
Selection.Column