如何检查每个单元格中的值从一列到另一列中的每个单元格

时间:2011-04-08 20:28:42

标签: excel-vba comparison excel-2007 vba excel

我有2组值,我需要突出显示2列的常用值(字母数字)。行数超过50,000行。有没有办法为它编写代码?基本上,我需要检查来自Col A的每个细胞对来自A2到A59000的Col I的每个细胞

1 个答案:

答案 0 :(得分:0)

一个想法:使用VBScript字典来避免Rows * Rows循环和实验模块:

Attribute VB_Name = "Module1"
' needs Reference to Microsoft Scripting Runtime (for Dictionary)

Option Explicit

Const cnRows = 1000
Const cnLChar = 80
Const cnFNum = 1000
Const cnLNum = 1100

Function IntRange(iFrom, iTo)
    IntRange = iFrom + Fix((iTo - iFrom) * Rnd())
End Function

Sub fill()
    Dim sngStart As Single
    sngStart = Timer
    Dim sheetTest As Worksheet
    Set sheetTest = Sheet2
    Dim nRow, nCol
    For nRow = 1 To cnRows
        For nCol = 1 To 2
            sheetTest.Cells(nRow, nCol) = Chr(IntRange(65, cnLChar)) & IntRange(cnFNum, cnLNum)
        Next
    Next
    With sheetTest.Cells.Interior
       .ColorIndex = 0
       .Pattern = xlSolid
       .PatternColorIndex = xlAutomatic
    End With
    sheetTest.Cells(nRow, 1) = Timer - sngStart
End Sub

Sub bruteForce()
    Dim sngStart As Single
    sngStart = Timer
    Dim sheetTest As Worksheet
    Set sheetTest = Sheet2
    Dim nRow1 As Integer
    Dim nRow2 As Integer
    For nRow1 = 1 To cnRows
        For nRow2 = 1 To cnRows
            If sheetTest.Cells(nRow1, 1) = sheetTest.Cells(nRow2, 2) Then
               With sheetTest.Cells(nRow1, 1).Interior
                    .ColorIndex = 8
                    .Pattern = xlSolid
                    .PatternColorIndex = xlAutomatic
               End With
            End If
        Next
    Next
    sheetTest.Cells(nRow1, 1) = Timer - sngStart
End Sub

Sub useDict()
    Dim sngStart As Single
    sngStart = Timer
    Dim sheetTest As Worksheet
    Set sheetTest = Sheet2
    Dim dicElms As New Scripting.Dictionary
    Dim nRow As Integer
    For nRow = 1 To cnRows
        dicElms(sheetTest.Cells(nRow, 1).Text) = 0
    Next
    For nRow = 1 To cnRows
        If dicElms.Exists(sheetTest.Cells(nRow, 2).Text) Then
           With sheetTest.Cells(nRow, 2).Interior
                .ColorIndex = 8
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
            End With
        End If
    Next
    sheetTest.Cells(nRow, 2) = Timer - sngStart
End Sub