我正在尝试编写一个宏来比较两列,如果值相等,那么它应该将另一个单元格的值复制到一个新单元格中。我写下面的宏:
Sub Value()
Dim rng1 As Range
Set rng1 = Worksheets("Sheet1").Range("L2:L11860")
Dim rng2 As Range
Set rng2 = Worksheets("Sheet1").Range("W2:W12000")
Dim rng3 As Range
Set rng3 = Worksheets("Sheet1").Range("A2:A12000")
Dim rng4 As Range
Set rng4 = Worksheets("Sheet1").Range("X2:X12000")
If rng1.Value = rng2.Value Then
rng3.Value = rng4.Value
End If
End Sub
以下代码行为Run Time error 13
提供了
If rng1.Value = rng2.Value Then
请帮助解决这个问题。
答案 0 :(得分:2)
这应该没有循环:
Sub Value()
Dim rng1 As Range
Set rng1 = Worksheets("Sheet1").Range("L2:L12000")
Dim rng2 As Range
Set rng2 = Worksheets("Sheet1").Range("W2:W12000")
Dim rng3 As Range
Set rng3 = Worksheets("Sheet1").Range("A2:A12000")
Dim rng4 As Range
Set rng4 = Worksheets("Sheet1").Range("X2:X12000")
rng3.Value = Worksheets("Sheet1").Evaluate("=IF(INDEX(" & rng1.Address(0, 0) & "=" & rng2.Address(0, 0) & ",)," & rng4.Address(0, 0) & ","""")")
End Sub
或者Dirk建议您可以:
Sub Value()
Dim rng1 As Range
Set rng1 = Worksheets("Sheet1").Range("L2:L12000")
Dim rng2 As Range
Set rng2 = Worksheets("Sheet1").Range("W2:W12000")
Dim rng3 As Range
Set rng3 = Worksheets("Sheet1").Range("A2:A12000")
Dim rng4 As Range
Set rng4 = Worksheets("Sheet1").Range("X2:X12000")
rng3.Value = Worksheets("Sheet1").Evaluate("=IF(" & rng1.Address(0, 0) & "=" & rng2.Address(0, 0) & "," & rng4.Address(0, 0) & ","""")")
End Sub