如何根据名称选择列而不使用范围(“A”)?

时间:2015-05-28 11:53:18

标签: excel vba excel-vba

我有以下代码,它完全正常。但是,我想要按名称选择列,而不是Range(“A”)。

Option Explicit
'// Campare and Hilight Unique
Sub CompareHighlightUnique()
Dim Range1 As Range
Dim Range2 As Range
Dim i As Integer
Dim j As Integer
Dim isMatch As Boolean

For i = 2 To Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
    isMatch = False
    Set Range1 = Sheets("Sheet1").Range("A" & i)
    For j = 1 To Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row
        Set Range2 = Sheets("Sheet2").Range("A" & j)
        If StrComp(Trim(Range1.Text), Trim(Range2.Text), vbTextCompare) = 0 Then
            isMatch = True
            Exit For
        End If
        Set Range2 = Nothing
    Next j
    If Not isMatch Then
        Range1.Interior.Color = RGB(255, 0, 0)
    End If
    Set Range1 = Nothing
Next i
End Sub

1 个答案:

答案 0 :(得分:0)

下面的更新代码

Option Explicit
'// Campare and Hilight Unique
Sub CompareHighlightUnique()
Dim Range1 As Range, Range2 As Range, i&, j&, isMatch As Boolean
Dim Z&: Z = Cells.Find("Column Name", , , , , , True).Column 'here
For i = 2 To Sheets("Sheet1").Cells(Rows.Count, Z).End(xlUp).Row 'here
    isMatch = False
    Set Range1 = Sheets("Sheet1").Cells(i, Z) 'here
    For j = 1 To Sheets("Sheet2").Cells(Rows.Count, Z).End(xlUp).Row 'here
        Set Range2 = Sheets("Sheet2").Cells(j, Z) 'and here
        If StrComp(Trim(Range1.Text), Trim(Range2.Text), vbTextCompare) = 0 Then
            isMatch = True
            Exit For
        End If
        Set Range2 = Nothing
    Next j
    If Not isMatch Then
        Range1.Interior.Color = vbRed
    End If
    Set Range1 = Nothing
Next i
End Sub

column name替换为所需的列名(变量Z