【问题标题】:Embedded "for each" loop condition is not true after first iteration第一次迭代后嵌入的“for each”循环条件不成立
【发布时间】:2017-08-22 14:25:15
【问题描述】:

以下宏用于将内容从一个工作表中的列标题下(列顺序可变,但列名相同)复制到另一个工作表(现在一列紧挨着另一列)。问题是在嵌入的 For Each 循环的第一次迭代之后,条件“cell = header”不再为真,因为“Next cell”显然还没有执行。有什么解决方法吗?还是我必须完全重写?

Sub CopyContentBelowHeadersToAnotherSheet ()

Dim headers As Range
Dim cell As Variant
Dim header As Variant
Dim CopiedHeaders As Variant
Dim is as Variant



Set headers = Workbooks("GL audit template 3.0.xlsm").Worksheets ("Sheet3").Range("A1:Z1")
CopiedHeaders = Array("DocumentNo", "G/L", "Type", "Tx", "Text", "BusA", "Doc. Date", "Amount in local cur.")
i = 1

For Each cell In headers
    For Each header In CopiedHeaders
         If cell = header Then ' this is no longer true after first iteration of this loop 
          cell.Offset(1, 0).Activate 
          Range(ActiveCell, ActiveCell.End(xlDown)).Copy
          Workbooks("GL audit template 3.0.xlsm").Worksheets("Sheet1").Activate
          Cells(2, i).Activate
          ActiveSheet.Paste
          i = i + 1
        End If
    Next header
Next cell

End Sub

【问题讨论】:

  • i =i+1 放在Next headernext cell 之间可以解决您的问题吗?
  • 不幸的是它没有,i = i + 1 比第一次迭代后变为不真实的单元格 = 标题条件位于代码的更下方

标签: vba excel


【解决方案1】:

请摆脱那些缓慢无用的ActivateActiveCell
我还没有测试过,但这应该会更好。

For Each cell In headers
    For Each header In CopiedHeaders
         If cell = header Then ' this is no longer true after first iteration of this loop 
          With cell
             Range(.Offset(1, 0), .Offset(1, 0).End(xlDown)).Copy
             Workbooks("GL audit template 3.0.xlsm").Worksheets("Sheet1").Cells(2, i).Paste
          End with
          i = i + 1    'edited
        End If
    Next header
Next cell

【讨论】:

  • 谢谢帕特里克。不幸的是,"Workbooks("GL audit template 3.0.xlsm").Worksheets("Sheet1").Cells(2, i).Paste" 行给了我“对象不支持此属性或方法”错误。跨度>
猜你喜欢
  • 2010-12-28
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 2019-06-05
  • 2018-07-07
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多