【问题标题】:For Each Vba excel it makes just 1 loop对于每个 Vba excel,它只进行 1 个循环
【发布时间】:2017-04-05 15:10:39
【问题描述】:

我有 3 张纸,我必须比较第一张和第二张纸中单元格的值,并在第三张中写出不同之处。

这里是代码

Dim keyRangeSh1 As String
Dim keyRangeSh2 As String
Dim keyRangeSh3 As String
Dim cellSh1 As Range
Dim cellSh2 As Range
Dim cellSh3 As Range

rowSh1 = 2
rowSh2 = 2
rowSh3 = 2

keyRangeSh1 = "C" & rowSh1
keyRangeSh2 = "C" & rowSh2
keyRangeSh3 = "C" & rowSh3
For Each cellSh1 In Sh1.Range(keyRangeSh1)
   For Each cellSh2 In Sh2.Range(keyRangeSh2)
   'if
   'rowsh1 = rowsh1 + 1
   'keyRangeSh1 = "C" & rowsh1 
   'endif
  Next cellSh2
Next cellSh1

它进入了第一轮,但它没有回到第二个单元格

【问题讨论】:

  • keyRangeSh1 = "C" & rowSh1 keyRangeSh2 = "C" & rowSh2 keyRangeSh3 = "C" & rowSh3 这些都是单个单元格(C2),因此不会发生循环。
  • 我增加keyRangeSh1:rowsh1 = rowsh1 + 1 keyRangeSh1 = "C" & rowsh1
  • 但是当您使用For Each cellSh1 In Sh1.Range(keyRangeSh1) 设置循环时,keyRangeSh1 已经设置为"C" & rowSh1,因此您的递增不起作用。
  • 此外,即使您增加 keyRangeSh1,您仍然指的是一个单元格。 C2 是一个单元格,C3 也是如此,C4 和 C5 也是如此。
  • 最好在开始循环之前计算出范围。如果您知道它从第 2 行开始并在变量 rowSh1 中的某个点结束,您可以使用 keyRangeSh1 = "C2:C" & rowSh1then For Each cellSh1 In Sh1.Range(keyRangeSh1)

标签: vba excel foreach


【解决方案1】:

你可以用这个:

Option Explicit

Sub main()
    Dim sh1 As Worksheet, sh2 As Worksheet

    Set sh1 = Worksheets("Sh1") '<--| change "Sh1" to your actual first sheet name
    Set sh2 = Worksheets("Sh2") '<--| change "Sh2" to your actual second sheet name

    With Worksheets("sh3") '<--| change "Sh3" to your actual third sheet name
        .Range(Union(.Range(sh1.UsedRange.SpecialCells(xlCellTypeConstants, xlNumbers).Address), .Range(sh2.UsedRange.SpecialCells(xlCellTypeConstants, xlNumbers).Address)).Address).FormulaR1C1 = "='" & sh1.Name & "'!RC - '" & sh2.Name & "'!RC"
        .UsedRange.Value = .UsedRange.Value
    End With
End Sub

【讨论】:

  • 为什么要将 UsedRange 的值设置为自己的值?
  • 去掉公式,只留下结果
  • 有道理,我没想到!
  • 如果您想保留公式,只需摆脱该代码行!如果它解决了您的问题,您可能希望将答案标记为已接受。谢谢!
  • 我会,但我不是提问者,我只是好奇:)。
猜你喜欢
  • 2016-02-26
  • 2021-07-05
  • 1970-01-01
  • 2018-04-05
  • 2014-01-25
  • 1970-01-01
  • 2018-02-13
  • 2018-10-09
  • 1970-01-01
相关资源
最近更新 更多