【问题标题】:Unable to populate a named range无法填充命名范围
【发布时间】:2019-09-29 07:07:36
【问题描述】:

我遇到了一个我自己无法解决的问题,想知道这里是否有人可以教育我我做错了什么?该代码的目的是将一行信息(大约 60 个单元格)转移到另一个工作表中。

-

为了增加一些清晰度(我的最后一个问题很难理解):

RProjekt 包含以下单元格:E6;F15;F17;F19;F21;F23;I6;I8;I10;I15;I17;I19;I21;I23

RBkriterier 包含以下单元格:F30:K30;F31:K31;F32:K32;F33:K33;F34:K34

冲洗器包含以下单元: F45:K45;F46:K46;F47:K47;F48:K48;F49:K49

-

我希望下面的代码能说明我想要完成的工作。有什么建议么?感谢您的帮助!

-

Dim Bkriterier As Range
Dim Pinformation As Range
Dim inser As Range
Dim AllProjectInformation as range

Set Pinformation = InputSheet_Utveckling.Range("RProjekt") '"InputSheet_Utveckling" is a worksheet
Set Bkriterier = InputSheet_Utveckling.Range("RBkriterier") ' The "R ..." are named ranges consisting of several cells
Set inser = InputSheet_Utveckling.Range("Rinser")
Set AllProjectInformation = Union(Pinformation, Bkriterier, inser)


Dim i As Integer
For i = 1 To AllProjectInformation.Cells.Count
    AllProjectInformation.Areas(i) = projectRow.Range(i) '"projectRow is from another routine that goes through a table looking for a project code. Once found, that specific row is (and the "address") is stored in projectRow of type ListRow
Next i

【问题讨论】:

  • 只是一个盲注:将'For i = 1 To AllProjectInformation.Cells.Count'更改为'For i = 1 To AllProjectInformation.Areas.Count?
  • 我认为您的问题是您通过UNION 创建了一个新的范围对象。您是否不尝试遍历这个新范围对象的每个单元格而不是使用Areas? > For each cl in AllProjectInformation............<code>............Next cl
  • For Each 是可靠地逐步遍历合并范围的单元格的唯一方法 - 如果您使用循环计数器,那么您最终将访问不在合并范围内的单元格(它将开始计算与第一个 Area 相邻但未包含在其中的单元格)
  • @timwilliams,太好了。谢谢你。我显然必须阅读更多关于领域的内容。您有任何替代代码的建议吗? “projectRow”是不同工作表上表格中的特定行,它包含大约 60 个单元格。我不确定如何在不使用索引的情况下遍历“projectRow”上的所有单元格。
  • @JvdV,请参见上文。我无法在一条评论中标记 2 个用户

标签: excel vba


【解决方案1】:

以下是从单个连续范围填充合并的非连续范围的非工作(For 循环计数器)和工作(For Each 循环)方法的比较:

Sub Tester()

    Dim rngMerged As Range, rngRow As Range, c As Range
    Dim i As Long

    'Yellow and grey areas
    Set rngMerged = Application.Union(Range("B2:B6"), Range("D2:D6"))

    'Green-shaded area
    Set rngRow = Range("F2:O2")

    'Here we're trying to fill rngMerged cell-by-cell from rngRow...

    'Method 1 - does not work as expected
    For i = 1 To rngMerged.Cells.Count
        rngMerged.Cells(i).Value = rngRow.Cells(i).Value
    Next i

    'Method 2 - fills as expected
    i = 0
    For Each c In rngMerged.Cells
        i = i + 1
        c.Value = rngRow.Cells(i).Value
    Next c

End Sub

方法 1 的结果:使用 For 循环计数器,我们最终只填充了合并范围的第一个区域(然后随着循环的进行延伸到该区域之外)

方法 2 结果:循环合并范围的 For Each 方法按预期命中每个单元格,我们可以使用 i 可靠地索引到单区域范围 rngRow.Cells

注意:合并范围的顺序将影响单元格在 For Each 循环中的循环顺序,因此您可以控制合并区域中单元格的方式映射到 projectRow 源范围内的单元格。

【讨论】:

  • 非常感谢。如此优雅,我真的很欣赏对“联合”行为的解释,这样我就可以避免类似的错误。附带说明一下,您是否建议尽可能多地使用“应用程序”(如果适用)以获得更稳定的代码和执行?
  • 我可能不会在所有可能的地方使用应用程序 - 通常仅用于联合/相交、屏幕更新、计算设置等,以及在 VBA 中使用工作表函数时。
猜你喜欢
  • 1970-01-01
  • 2016-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-14
  • 1970-01-01
相关资源
最近更新 更多