【发布时间】:2017-12-01 05:28:01
【问题描述】:
在工作表中,有两个命名范围,每个范围只包含一行,例如Range1 = Range("B5:H5") 和 Range2 = Range("B9:H9")。我的问题是:我如何引用 Range1 中的一个单元格,比如 C5,以及 Range2 中的一个单元格,比如 VBA 中的 C9,以便我可以对这两个单元格中的值做一些事情? VBA 应该只为活动列运行。先感谢您。
【问题讨论】:
在工作表中,有两个命名范围,每个范围只包含一行,例如Range1 = Range("B5:H5") 和 Range2 = Range("B9:H9")。我的问题是:我如何引用 Range1 中的一个单元格,比如 C5,以及 Range2 中的一个单元格,比如 VBA 中的 C9,以便我可以对这两个单元格中的值做一些事情? VBA 应该只为活动列运行。先感谢您。
【问题讨论】:
也许你应该看到这个链接。
How to avoid using Select in Excel VBA macros
正如西达斯所说,
应该避免使用 .Select/.Activate/Selection/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
【讨论】:
【讨论】:
这行得通吗?
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)
【讨论】:
通过使用Cells 方法,您可以使用Range1.Row(和Range2.Row)指定适当的行,并使用(如果我理解正确的话)Selection.Column 指定适当的列。
所以也许是这样的:
Dim Range1 As Range
Dim Range2 As Range
Set Range1 = Range("B5:H5")
Set Range2 = Range("B9:H9")
'Display the value in row 5 for the current column
MsgBox Cells(Range1.Row, Selection.Column).Value
'Display the value in row 9 for the current column
MsgBox Cells(Range2.Row, Selection.Column).Value
'Change row 9 to be the value from row 5
Cells(Range2.Row, Selection.Column).Value = Cells(Range1.Row, Selection.Column).Value
'Display the updated value in row 9 for the current column
MsgBox Cells(Range2.Row, Selection.Column).Value
【讨论】: