简体   繁体   中英

How to create Named Ranges using a loop in Excel VBA?

I would like to create named ranges in my Excel sheet which should be copied to another worksheet later.
I have created a code that names the ranges like this:

Sub Sample1()

Dim RangeName As String

    RangeName1 = Worksheets("DB_Elements").Range("B3")
    ThisWorkbook.Names.Add Name:=RangeName1, RefersTo:=Worksheets("DB_Elements").Range("B3:V14")
    
    RangeName2 = Worksheets("DB_Elements").Range("B17")
    ThisWorkbook.Names.Add Name:=RangeName2, RefersTo:=Worksheets("DB_Elements").Range("B17:V28")

However, this needs to be repeated another 85 times. So I need a loop in my VBA that would create each time a new named range based on the "B" cell value which is always offset 14 rows down. The named ranges always consist of 12 rows and 21 columns.

Try this:

Sub Sample1()
  Dim i As Long
  Dim j As Long
  With Worksheets("DB_Elements")
    For i = 1 To 85
      j = (i - 1) * 14 + 3
      ThisWorkbook.Names.Add Name:=.Range("B" & j), RefersTo:=.Range("B" & j & ":V" & (j + 11))
    Next
  End With
End Sub

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