我怎么能缩短这段代码?

时间:2016-03-09 08:15:08

标签: excel vba

如何缩短此代码?

r = 11

Do While Not tgtWSheet.Cells(r, 2) = "0"

    If tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 1, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 2, 2) Or _
        tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 3, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 4, 2) Or _
        tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 5, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 6, 2) Or _
        tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 7, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 8, 2) Or _
        tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 9, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 10, 2) Or _
        tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 11, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 12, 2) Or _
        tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 13, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 14, 2) Or _
        tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 15, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 16, 2) Or _
        tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 17, 2) Or tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + 18, 2) Then

        MsgBox "Duplicate Record Found!"
        Exit Sub

    Else

        r = r + 1

    End If

Loop

3 个答案:

答案 0 :(得分:1)

使用WorksheetFunction.CountIF,您可以计算您的情况下特定值范围(r&amp;“2)在某个范围内重复的次数,并使用该结果我们可以计算该值是否重复。< / p>

r = 11

Do While Not tgtWSheet.Cells(r, 2) = "0"
    IF WorksheetFunction.CountIF(tgtWSheet.Range("B" & r & ":S" & r),tgtWSheet.Range("B" & r)) > 1 Then

        MsgBox "Duplicate Record Found!"
        Exit Sub

    Else

        r = r + 1

    End If

Loop

答案 1 :(得分:0)

您可以使用&#34;范围&#34;的.Find()方法对象

    Option Explicit

    Sub main()

    Dim rowOffset As Long
    Dim tgtWSheet As Worksheet

    Set tgtWSheet = ThisWorkbook.Worksheets("tgtW") '<== adapt to your needs

    With tgtWSheet.Cells(11, 2)
        Do While .Offset(rowOffset).Value <> "0"

            If .Offset(rowOffset + 1).Resize(18).Find(What:=.Offset(rowOffset), LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False) Is Nothing Then
                rowOffset = rowOffset + 1
            Else
                MsgBox "Duplicate Record Found!"
                Exit Sub
            End If

        Loop
    End With

    End Sub

答案 2 :(得分:-1)

使用For循环:

 r = 11

Do Until tgtWSheet.Cells(r, 2) = "0"
    for i = 1 to 18
        If tgtWSheet.Cells(r, 2) = tgtWSheet.Cells(r + i, 2) Then
            MsgBox "Duplicate Record Found!"
            Exit Sub
        Else
            r = r + 1
        End If
    next
Loop

虽然小心!代码在遇到第一个“0”时停止。

奖励:Do While Not = Do Until