2017-04-05 69 views
-1

我有3個工作表,我必須比較第一個和第二個工作表中的單元格值,並在第三個工作表中寫入不同的值。對於每個VBA excel它只會產生1個循環

下面的代碼

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 

它使第一輪,但它沒有回到第二單元

+2

'keyRangeSh1 = 「C」 &rowSh1 keyRangeSh2 =「C」&rowSh2 keyRangeSh3 =「C」&rowSh3'這些都是單個單元格('C2'),所以不會出現循環。 – Kyle

+0

我增加keyRangeSh1:rowsh1 = rowsh1 + 1 keyRangeSh1 =「C」&rowsh1 – Alessandro95

+1

但是當你設置循環'For Each cellSh1在Sh1.Range(keyRangeSh1)'中,'keyRangeSh1'已經設置爲'「C」 &rowSh1'因此你的增值什麼都不做。 – Kyle

回答

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 
+0

爲什麼將UsedRange的值設置爲自己的值? –

+0

以擺脫公式,只留下他們的結果 – user3598756

+0

有道理,我沒有想到這個! –