比较VBA中列的单元格值

时间:2019-01-01 09:05:00

标签: excel vba

我在列中有以下数据:

8856
8867
8876
8856
8898

我的目标是比较列的每个单元格,如果值相同则执行if语句。

Private Sub CommandButton2_Click()

Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim C1row As Long
Dim C2row As Long
Dim C2TotalRows As Long
Dim CustID As String

Set sht1 = Worksheets("Report")

sht1.Activate
C2TotalRows = Application.CountA(Range("A:A"))
C1row = 2

Do While sht1.Cells(C1row, 3).Value <> ""

    CustID = sht1.Cells(C1row, 3).Value

    For C2row = 2 To C2TotalRows

        If CustID = Cells(C2row, 3).Value Then
            MsgBox CustID
            Exit For
        End If

    Next
    C1row = C1row + 1

Loop
End Sub

3 个答案:

答案 0 :(得分:0)

仅假设,由于范围“ A:A”,我看到C2TotalRows=C2TotalRows = Application.CountA(Range("A:A"))等于1。因此,For C2row = 2 To C2TotalRows此循环将永远不会运行。尝试指定其他单元格范围。

答案 1 :(得分:0)

您似乎想知道CustID(例如8856)在数据中出现的频率以及行号。 为此,我创建了一个简单的class cInfo,然后将信息汇总到dictionary中。最后,我只是打印了信息,但您可以添加要运行的代码

这是cInfo类

Option Explicit

Public rowNr As String
Public ocur As Long

这就是收集信息的代码

Sub UniqueValues()
Dim dict As Scripting.Dictionary
Dim rg As Range, sngCell As Range
Dim i As Long
Dim lRow As Long
Dim cellInfo As cInfo

    lRow = Range("A1").End(xlDown).Row      'Assumption now free rows and at least on entry in row 2
    Set rg = Range("A2:A" & lRow)
    Set dict = New Dictionary

    For Each sngCell In rg
        If dict.Exists(sngCell.Value) Then
            dict.Item(sngCell.Value).ocur = dict.Item(sngCell.Value).ocur + 1
            dict.Item(sngCell.Value).rowNr = dict.Item(sngCell.Value).rowNr & ";" & CStr(sngCell.Row)
        Else
            Set cellInfo = New cInfo
            cellInfo.rowNr = CStr(sngCell.Row)
            cellInfo.ocur = 1
            dict.Add sngCell.Value, cellInfo
        End If
    Next

    ' Do sth here. I will print some info
    For i = 0 To dict.Count - 1
        Debug.Print "CustID:", dict.Keys(i), dict.Items(i).ocur, "occurence(s) in rows", dict.Items(i).rowNr
    Next

End Sub

这与您提供的示例数据配合正常

enter image description here

输出

enter image description here

答案 2 :(得分:0)

尝试用此方法修改您的代码:

Private Sub CommandButton2_Click()
  Dim sht1 As Worksheet
  Dim C1row As Long
  Dim CustID As String
  Dim R As Range

  Set sht1 = Worksheets("Report")
  sht1.Activate
  C1row = 2

  Do While sht1.Cells(C1row, 3).Value <> ""
    CustID = sht1.Cells(C1row, 3).Value
    Set R = sht1.Range("C:C").Find(CustID, sht1.Cells(C1row, 3))
    If R.Row > C1row Then
      MsgBox CustID
    End If
    C1row = C1row + 1
  Loop
End Sub

祝你好运。

参考:Range.Find method (Excel)