简体   繁体   English

如何使用 Excel VBA 中的循环创建命名范围?

[英]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.我想在我的 Excel 工作表中创建命名范围,稍后应将其复制到另一个工作表。
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.但是,这需要再重复 85 次。 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.所以我需要在我的 VBA 中创建一个循环,每次都会创建一个基于“B”单元格值的新命名范围,该单元格值总是向下偏移 14 行。 The named ranges always consist of 12 rows and 21 columns.命名范围总是由 12 行和 21 列组成。

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

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

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