0

以下代码类似于 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
4

1 回答 1

0

您应该TargetCell.Formula在第二个块中使用。在我下面的示例代码中,Sheet1 中的 A1 具有=SUM(B1:C1). 在 Sheet2 中,它位于 D1 中。它返回正确的地址。

Sub Test()
    Dim TargetCell As Range
    Dim TargetF, TestS As String
    Set TargetCell = Sheet1.Range("A1")
    TargetF = TargetCell.Formula
    TestS = Sheet2.Cells.Find(What:=TargetF, LookIn:=xlFormulas).Address
    MsgBox TestS 'Returns D1.
End Sub

让我们知道这是否有效。

于 2013-10-25T05:46:22.540 回答