You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在多工作表中查找重复项的VBA函数实现需求

Dual-Worksheet Duplicate Check VBA Function

Hey there! Let's get that dual-worksheet duplicate finder up and running. Your single-sheet function works great, but the issue with your pseudocode is that you can't use & to combine two ranges—we need to use Excel's Union function to merge those two worksheet ranges into a single searchable area.

Option 1: Combine Ranges with Union (Cleanest Approach)

This method merges the two target ranges first, then runs a single Find operation across both sheets:

Function FindDuplicate(factnr) As Boolean
    Dim combinedRange As Range
    Dim foundCell As Range
    
    ' Merge the D6:D206 ranges from both sheets into one range object
    Set combinedRange = Union( _
        Worksheets("Sheet 1").Range("D6:D206"), _
        Worksheets("Sheet 2").Range("D6:D206") _
    )
    
    ' Search the combined range for the target value
    Set foundCell = combinedRange.Find( _
        What:=factnr, _
        LookIn:=xlValues, _
        LookAt:=xlWhole, _
        MatchCase:=False _
    )
    
    ' Return True if found, False otherwise
    FindDuplicate = Not foundCell Is Nothing
End Function

Option 2: Step-by-Step Worksheet Check (Alternative)

If you prefer to check one sheet at a time (which can be slightly faster if the value is often in the first sheet), use this version:

Function FindDuplicate(factnr) As Boolean
    Dim foundCell As Range
    
    ' Check Sheet 1 first
    With Worksheets("Sheet 1").Range("D6:D206")
        Set foundCell = .Find(factnr, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
        If Not foundCell Is Nothing Then
            FindDuplicate = True
            Exit Function ' No need to check Sheet 2 if we found it here
        End If
    End With
    
    ' Check Sheet 2 if Sheet 1 had no match
    With Worksheets("Sheet 2").Range("D6:D206")
        Set foundCell = .Find(factnr, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
        If Not foundCell Is Nothing Then
            FindDuplicate = True
            Exit Function
        End If
    End With
    
    ' Value not found in either sheet
    FindDuplicate = False
End Function

Why Your Pseudocode Didn't Work

The line Worksheets("Sheet 1").Range("D6:D206") & ("Sheet 2").Range("D6:D206") uses the string concatenation operator (&), which tries to turn the ranges into text instead of merging them as range objects. Using Union is the correct way to combine multiple ranges for a single search.

内容的提问来源于stack exchange,提问作者Erwin Hermsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:39:03