.Find函数和Offset单元格用于常量而不是公式

时间:2013-10-25 05:16:17

标签: vba excel-vba offset vlookup excel

以下代码类似于Vlookup函数。想知道为什么相同的For Each ... Next循环在应用于常量时有效,但在应用于公式时则无效。

谢谢

Dim ws1 As Worksheet,ws2 As Worksheet Dim SourceRange作为范围,TargetRange作为范围,TargetCell作为范围,SourceCell作为范围,SourceColumn作为范围,TargetColumn作为范围,TargetRangeConstant作为范围,TargetRangeFormula作为范围

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

1 个答案:

答案 0 :(得分: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

如果有效,请告诉我们。