【问题标题】:.Find function and Offset cells working for constants but not formulas.查找适用于常量但不适用于公式的函数和偏移单元格
【发布时间】:2013-10-25 05:16:16
【问题描述】:

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

【问题讨论】:

    标签: vba excel offset vlookup


    【解决方案1】:

    您应该在第二个块中使用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
    

    让我们知道这是否可行。

    【讨论】:

    • 非常感谢!当我执行工作簿中的代码时,它就像魔术一样工作。在 .Find 函数中将 TargetCell 编辑为 TargetCell.Formula。
    • 很高兴它对你有用。如果通过单击检查图标有帮助,请接受以上作为答案。谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多