如何在VBA的命名行范围内的活动列中使用单元值

问题描述:

在工作表中,有两个命名范围,每个范围只包含一行,例如,范围1 =范围(“B5:H5”)和范围2 =范围(“B9:H9”)。我的问题是:如何在Range1中引用一个单元格,比如说C5,以及Range2中的单元格,比如说VBA中的C9,以便我可以用这两个单元格中的值做些什么? VBA只能运行在活动列中。先谢谢你。如何在VBA的命名行范围内的活动列中使用单元值

使用可以

Range1.offset() 

方法指相邻小区

可以参考here详细。

+0

谢谢,KNVB。如果用户更改电子表格布局,我希望使用范围名称而不是偏移量。我可以使用:variable1 = ActiveSheet.Columns(ActiveCell.Column).Row(5)和variable2 = ActiveSheet.Columns(ActiveCell.Column).Row(9),但是这不使用命名范围。 – Leon

这项工作?

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) 
+0

谢谢你,保罗。我会尝试。 – Leon

通过使用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 
+0

谢谢,YowE3K。我使用细胞。它的作品非常漂亮。 – Leon

也许你应该可以看到这个链接。

How to avoid using Select in Excel VBA macros

由于Siddarth说,为什么。选择/ .Activate /选择/ 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