简体   繁体   中英

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. 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. I'm thinking the best way to do this is using find, but again, I'm very new to this. 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).

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

' 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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