首页 > 解决方案 > Excel VBA,使用循环检查现有值

问题描述

我有 70 个带有电话号码的姓名,如果有重复的电话号码并删除该号码,我如何使用 For 或 if else 语句或两者检查。提前致谢!

Sub GenerateNames()
Dim ssheet1 As Worksheet
Dim rngen As Worksheet
Dim rnsheet As Worksheet

Dim i As Integer, intValueToFind As Integer
intValueToFind = 12345

Set ssheet1 = ThisWorkbook.Sheets("Sheet1")
Set rngen = ThisWorkbook.Sheets("RnGen")
Set rnsheet = ThisWorkbook.Sheets("RandomNames")

rngen.Range("A3:A70").Copy rnsheet.Range("A3:A70")
ssheet1.Range("B3:B70").Copy rnsheet.Range("B3:B70")


For b = 1 To 70
    If Cells(b, 2).Value = intValueToFind Then
        MsgBox ("Found value on row " & i)
        Exit Sub
    End If
Next b

MsgBox ("Value not found in the range!")
End Sub

标签: excelvba

解决方案


如果要检查重复的电话号码:

Public Sub CheckForDupes()
    For b = 1 To 70
        For c = b + 1 To 70
            If Cells(b, 2).Value = Cells(c, 2).Value Then
                MsgBox ("Rows " & b & " and " & c & "are duplicates.")
            End If
        Next c
    Next b
End Sub

推荐阅读