Excel VBA:复制多个命名范围的循环

时间:2017-11-11 04:48:49

标签: excel-vba loops named-ranges vba excel

我想复制几个命名范围。范围有一个设置命名约定,带有一个短字符串,然后是数字(例如,Body1,Body2等)。

我的解决方法循环遍历每个工作表名称,并复制范围B2:C50而不是每个命名范围,这是我更喜欢的。

代码:

Dim Bnum As Integer          'Bnum is Loop Counter
Dim Nbodies As Integer       'Nbodies is how many loops should go
Dim BodyNum As String

'BodyNum is the sheet name where the named range is (and also the named range I`d like to copy). The named ranges are workbook wide in this case


Nbodies = Range("N.Bodies")  'Called from elsewhere in the workbook

Bnum = 1                    'Initial counter set
BodyNum = "Body" & Bnum     'Name of worksheet+named range which I want to copy

Do Until Bnum = Nbodies + 1
    Workbooks(Wkbk).Activate
    Worksheets(BodyNum).Range("B2:C50").Copy

'Copies range manually definied in vba B2:C50 in this case. Want to copy named range with the same name as Bodynum, varying the digit for each loop

    Workbooks(Inputbk).Activate     'The paste portion works fine
    Selection.PasteSpecial Paste:=xlPasteValues
    Call Cursor.Cursor
    Workbooks(Wkbk).Activate
    Bnum = Bnum + 1         'Iterates loop counter
    BodyNum = "Body" & Bnum
Loop

1 个答案:

答案 0 :(得分:0)

我的理解是你有一组名为“Body1”的工作表。“BodyN”,每个工作表都有一个带有工作表本身名称的命名范围。

你提到你Want to copy named range with the same name as Bodynum

然后你应该做的就是转这一行:

Worksheets(BodyNum).Range("B2:C50").Copy

进入这个:

Worksheets(BodyNum).Range(BodyNum).Copy