以下代码类似于 Vlookup 函数。想知道为什么相同的 For Each...Next 循环在应用于常量时有效,但在应用于公式时无效。
谢谢
Dim ws1 As Worksheet, ws2 As Worksheet
Dim SourceRange As Range, TargetRange As Range, TargetCell As Range,
Dim SourceCell As Range, SourceColumn As Range, TargetColumn As Range,
Dim TargetRangeConstant As Range, TargetRangeFormula As Range
On Error Resume Next
'set Worksheets and Ranges
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet1")
Set SourceRange = ws1.Range("A:A")
Set TargetRange = ws2.Range("L:L")
Set SourceColumn = ws1.Range("C:C")
Set TargetColumn = ws2.Range("O:O")
Set TargetRangeConstant = TargetRange.SpecialCells(xlConstants)
Set TargetRangeFormula = TargetRange.SpecialCells(xlFormulas)
'For Constants
For Each TargetCell In TargetRangeConstant
Set SourceCell = SourceRange.Find(What:=TargetCell, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not TargetCell Is Nothing Then
'"copies" cells in source to target
TargetCell.Offset(, TargetColumn.Column - TargetRange.Column) = SourceCell.Offset(, SourceColumn.Column - SourceRange.Column)
End If
Next
'Same Function but for Formulas
For Each TargetCell In TargetRangeFormula
Set SourceCell = SourceRange.Find(What:=TargetCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not TargetCell Is Nothing Then
'"copies" cells in source to target
**TargetCell.Offset(, TargetColumn.Column - TargetRange.Column) = SourceCell.Offset(, SourceColumn.Column - SourceRange.Column)**
End If
Next