简体   繁体   English

VBA Excel设置动态命名范围

[英]vba excel set dynamic named ranges

I want to set all the named range in one variable and export to PDF. 我想在一个变量中设置所有命名范围,然后导出到PDF。 I am able to do when I manually enter all the named range. 当我手动输入所有命名范围时,我就能做到。 My problem is named range are variable, sometime it will have one some time it will have more than 10. Please advice...I tried with following codes. 我的问题是命名范围是变量,有时它将有一个,有时会大于10。请咨询...我尝试使用以下代码。

Dim wbBook As Workbook
Dim nName As Name

Set wbBook = ActiveWorkbook
Set nName=wbBook.Names

Set rs = wbBook.Range(nNames)
rs.Select
Selection.ExportAsFixedFormat xlTypePDF, strPath, , , False

But below code works for me, when I enter range name manually.. 但是,当我手动输入范围名称时,以下代码对我有用。

Set rs = wbBook.Range("Page_1,Page_2,Page_3")
rs.Select
Selection.ExportAsFixedFormat xlTypePDF, strPath, , , False

You can't pass a collection (many objects) to an object variable (single object). 您不能将集合 (许多对象)传递给对象变量 (单个对象)。 You need to loop through the collection's objects. 您需要遍历集合的对象。 Usually we do this with a For Each loop, but in this case, as I needed to set the first element separately because of the Union , I have used a simple For loop. 通常,我们使用For Each循环来执行此操作,但是在这种情况下,由于需要使用Union来分别设置第一个元素,因此我使用了一个简单的For循环。

Also, avoid using .Select if you can. 另外,请避免使用.Select如果可以)。 Just use your objects directly. 只需直接使用您的对象。

Also note that you are talking about all the named ranges in the Workbook, and this might cause problems if you have named ranges in multiple worksheets. 另请注意,您正在谈论工作簿中的所有命名范围,如果在多个工作表中都命名了范围,则可能会引起问题。 I haven't tested, but I doubt it would work. 我还没有测试过,但是我怀疑它会起作用。

Dim wbBook As Workbook
Dim i As Integer
Dim rs As Range

Set wbBook = ActiveWorkbook
Set rs = wbBook.Names(1).RefersToRange
For i = 2 To wbBook.Names.Count
   Set rs = Union(rs, wbBook.Names(i).RefersToRange)
Next

rs.ExportAsFixedFormat xlTypePDF, strPath, , , False

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

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