我想根据Excel工作表中不同单元格中的值进行查询,并同时对这些值所在的行进行着色。当前代码仅对单行进行着色,然后循环停止。你能帮我吗,我应该在哪里修复代码以将循环应用于整个表?
Sub SearchAndHighlightIE()
Dim ws As Worksheet
Dim searchRange As Range
Dim foundCell As Range
Dim firstAddress As String
Dim searchTerm As String
' Kullanicidan arama terimi al
'searchTerm = InputBox("Aranacak kelimeyi giriniz:", "Arama Terimi")
' Eger kullanici bir sey girmeden iptal ederse, makroyu sonlandir
'If searchTerm = "" Then Exit Sub
' Aktif çalisma sayfasini ayarla
Set ws = ActiveSheet
' Arama yapilacak alan (tüm sayfa varsayilan olarak)
Set searchRange = ws.UsedRange
' Arama terimiyle ilk bulusu bul
Set foundCell0 = searchRange.Find(What:="Ýmal Edilen", LookIn:=xlValues, LookAt:=xlPart)
Set foundCell1 = searchRange.Find(What:="SLDPRT", LookIn:=xlValues, LookAt:=xlPart)
' Eger bir sonuç bulunursa
If Not foundCell0 Is Nothing Then
firstAddress0 = foundCell0.Address
If Not foundCell1 Is Nothing Then
firstAddress1 = foundCell1.Address
Do
' Hücreyi sariyla isaretle
foundCell0.EntireRow.Interior.Color = RGB(255, 255, 153)
' Sonraki bulusu ara
Set foundCell0 = searchRange.FindNext(foundCell0)
Loop While Not foundCell0 Is Nothing And foundCell0.Address <> firstAddress0
Else
MsgBox "Aranan terim bulunamadi."
End If
End If
End Sub
假设您的数据如下所示。
我们正在
Durukal
中搜索 Column 2
,在 Gurkan
中搜索 Column 12
。因此,根据您的要求,只有行 3
和 13
应该着色。
如果这就是你想要的,那就试试这个。
我已经对代码进行了注释,因此您应该不会在理解它时遇到问题。如果你是这样的话,那就直接问吧。
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim HighLightRange As Range
Dim VisibleAreas As Areas
Dim LastArea As Range
Dim lRow As Long
Dim i As Long
Dim FirstSearch As String
Dim SecondSearch As String
'~~> Change this to the relevant sheet
Set ws = Sheet1
FirstSearch = "Durukal"
SecondSearch = "Gurkan"
With ws
'~~> Remove any filters
.AutoFilterMode = False
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
With .Range("A1:N" & lRow)
'~~> Filter the data based on 1st column
.AutoFilter Field:=2, Criteria1:="Durukal"
'~~> Filter the data based on 2nd column. This way you
'~~> will get rows which will have both search terms
.AutoFilter Field:=12, Criteria1:="Gurkan"
'~~> This is the filtered range
Set HighLightRange = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
'Debug.Print HighLightRange.Address
End With
'~~> Remove any filters
.AutoFilterMode = False
End With
'~~> Check if filtering returned any range
If Not HighLightRange Is Nothing Then
'~~> Check if there are multiple areas
If HighLightRange.Areas.Count > 1 Then
Set VisibleAreas = HighLightRange.Areas
'~~> Color the areas except the last empty one
For i = 1 To VisibleAreas.Count - 1
VisibleAreas(i).Interior.Color = RGB(255, 255, 153)
Next i
Else
'~~> Only one area was found, color it directly
HighLightRange.Interior.Color = RGB(255, 255, 153)
End If
Else
MsgBox "Both terms not found in the same row"
End If
End Sub