简体   繁体   English

Excel:命名范围为 VBA

[英]Excel: Named range with VBA

I'm trying to define a named range in Excel using VBA.我正在尝试使用 VBA 在 Excel 中定义一个命名范围。 Basically, I have a variable column number.基本上,我有一个可变的列号。 Then a loop runs to determine the first empty cell in that particular column.然后循环运行以确定该特定列中的第一个空单元格。 Now I want to define a named range from row 2 of that particular column to the last cell with data in that column (first empty cell - 1).现在我想定义一个命名范围,从该特定列的第 2 行到该列中包含数据的最后一个单元格(第一个空单元格 - 1)。

For example, column 5 is specified, which contains 3 values.例如,指定了第 5 列,其中包含 3 个值。 My range would then be (2,5)(4,5) if I'm correct.如果我是正确的,那么我的范围将是 (2,5)(4,5)。 I'm just wondering how to specify this range using only integers instead of (E2:E4).我只是想知道如何仅使用整数而不是 (E2:E4) 来指定此范围。 Is it at all possible?有可能吗?

I found this code to define a named range:我发现这段代码定义了一个命名范围:

'Change the range of cells (A1:B15) to be the range of cells you want to define
    Set Rng1 = Sheets("Sheet1").Range("A1:B15") 
    ActiveWorkbook.Names.Add Name:="MyRange", RefersTo:=Rng1

Could anyone nudge me into the right direction to specify this range using integers only?任何人都可以将我推向正确的方向以仅使用整数指定此范围吗?

As your targeting a range of E2:E4 you would need to specify the cell locations.由于您的目标范围为 E2:E4,您需要指定单元格位置。 The below function might be of use to you, pass it the column number eg 5 and it will retunn the address so 5=E and 27=AA下面的 function 可能对您有用,将列号传递给它,例如 5,它将返回地址,因此 5=E 和 27=AA

ColLetter = ColNo2ColRef(colNo)
Set Rng1 = Sheets("Sheet1").Range(ColLetter & "2:" & ColLetter & "4") 
ActiveWorkbook.Names.Add Name:="MyRange", RefersTo:=Rng1

Function ColNo2ColRef(ColNo As Long) As String
    ColNo2ColRef = Split(Cells(1, ColNo).Address, "$")(1)
End Function

Hope this helps希望这可以帮助

EDIT: Or:编辑:或者:

Set rng = Range(Cells(2, 5), Cells(4, 5)) 'E2:E4
ActiveWorkbook.Names.Add Name:="MyRange", RefersTo:=Rng

or alternatively或者

Sub test()
Set rng1 = Cells(2, 2) 'B2

Set rng2 = rng1.Resize(3, 1) 'B2:B4
'or
Set rng2 = Range(rng1, Cells(4, 2)) 'B2:B4

End Sub

or do it directly without looping using或者直接做而不循环使用

With Sheet1
    col = 5 'variable col
    Set rng1 = .Range(.Cells(2, col), .Cells(.Rows.Count, col).End(xlUp))
    End With

which is the same as这与

with sheet1
    Set rng1 = .Range(.Range("E2"), .Range("E" & .Rows.Count).End(xlUp))
    end with

EDIT: If you're setting up named ranges to change dynamically then you don't need VBA.编辑:如果您正在设置命名范围以动态更改,那么您不需要 VBA。 Enter this directly into the named range in Excel and leave it to auto adjust automatically between E2 and whatever the last item is (assuming no blanks).将此直接输入到 Excel 中的命名范围中,并让它在 E2 和最后一项之间自动调整(假设没有空格)。 =$E$2:INDEX($E$2:$E$5000,COUNTA($E$2:$E$5000)) (Extend 5000 if you need need more rows) =$E$2:INDEX($E$2:$E$5000,COUNTA($E$2:$E$5000)) (如果需要更多行,请扩展 5000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM