对于每个Vba excel,它只进行1次循环

时间:2017-04-05 15:10:40

标签: excel vba excel-vba foreach

我有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

它进行第一轮但不会回到第二轮

1 个答案:

答案 0 :(得分:0)

你可以用这个:

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