简体   繁体   English

根据单元格值创建动态范围

[英]Creating Dynamic Range based on cell value

I'm new to VBA and I'm trying to create dynamic ranges based on cell values contained in column A. There are many ranges on the same sheet and the size of each range will change, thus I cannot identify a cell as the starting point for a range, since it will change.我是 VBA 新手,我正在尝试根据 A 列中包含的单元格值创建动态范围。同一张表上有很多范围,每个范围的大小都会改变,因此我无法将单元格识别为起始指向一个范围,因为它会改变。 I have a list of the different range names in column A of Sheet 2, which I can use to create the different ranges if needed.我在工作表 2 的 A 列中有一个不同范围名称的列表,如果需要,我可以使用它来创建不同的范围。 I'm thinking the best way to do this is using find, but again, I'm very new to this.我认为最好的方法是使用 find,但同样,我对此很陌生。 Here's what I have so far (not much, I know).这是我到目前为止所拥有的(不多,我知道)。 Any help is greatly appreciated!任何帮助是极大的赞赏! Thanks!谢谢!

 Sub NameRange()

Dim rngselect As Range, FinalRange As Range, cell As Range
Dim ws As Worksheet

Set ws = Worksheets("OOE")
Set rngselect = ws.Range("$A:Z")

ws.Columns(i, 1).Find(California).Select
.Name = "Cali"

End Sub

I've done this before and it's not as simple as it sounds.我以前做过这件事,但并不像听起来那么简单。 Named ranges are properties of the entire workbook and therefore must be unique.命名范围是整个工作簿的属性,因此必须是唯一的。 VBA will NOT generate an error if you change the range of a name (nor will it notify you).如果您更改名称的范围,VBA 不会产生错误(它也不会通知您)。

With that being said, - don't select the range there is no need.话虽如此, - 不要选择不需要的范围。 - since you are restricted to column A use a loop in case the find value is in column B - 由于您仅限于 A 列,因此如果查找值在 B 列中,请使用循环

' Worksheet with names
Dim name_ws as Worksheet
' Assuming you're worksheet with the names is in the same workbook and named "Names"
Set name_ws = ThisWorkbook.Worksheets("Names")

' Find might be better but I haven't had my coffee so you'll get the double loop
for j = 1 to name_ws.Cells.SpecialCells(xlCellTypeLastCell).Row
   for i = 1 to ws.Cells.SpecialCells(xlCellTypeLastCell).Row
      if ws.Cell(i, 1) = name_ws.Cells(j, 2) then _
         Range(ws.Cell(i,1), ws.Cell(i, 26)).Name = name_ws.Cells(j, 1)
   next i
next j

Please note : ws is your variable and you don't specify the start and end cell of your Named range in the question so I just went 26 cells over.请注意:ws 是您的变量,您没有在问题中指定命名范围的开始和结束单元格,所以我只检查了 26 个单元格。

Please note : I am assuming Column B of the worksheet with the names contains the search variable and Column A contains the name you want to use请注意:我假设带有名称的工作表的 B 列包含搜索变量,而 A 列包含您要使用的名称

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

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