简体   繁体   中英

How do I select a column based on its name and not using range(“A”)?

I have the following code and it works perfectly fine. But instead of Range("A"), I want to select a column by its name.

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

your updated code below

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

replace column name with required column name (variable Z )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM