如何选择其值中包含特定文本的列中的单元格

时间:2018-12-19 16:46:57

标签: excel vba excel-vba

我正在尝试使包含的单元格与我搜索的某些文本条件匹配。

我不断收到错误消息

  

运行时错误424需要对象

第12行

cell = Sheets("Sheet1").Range("A" & row_num)

我不确定为什么吗?

任何人和所有对此的帮助将不胜感激!

Option Compare Text

Sub FindingColumn()
Dim Col1Rng As Range, Col3Rng As Range
Dim Column1Search As String, Column2Search As String, Column3Search As 
String
row_num = 0

Column1Search = InputBox("Col 1 Criteria: ")

Do
DoEvents
row_num = row_num + 1
cell = Sheets("Sheet1").Range("A" & row_num)
    If Col2Rng = Empty And InStr(cell, Column1Search) Then
        Col2Rng = cell.Address(0, 0)
    ElseIf InStr(cell, Column1Search) Then
        Col2Rng = Col2Rng & "," & cell.Address(0, 0)

    End If
Loop Until cell = ""

Range(Col2Rng).Select
End Sub 

1 个答案:

答案 0 :(得分:0)

这应该作为您尝试做的事情的基础

Sub FindingColumn()
    Dim Col1Rng As Range, Column1Search As String, foundCellCol1 As Range
    Set Col1Rng = ActiveSheet.Range("A:A")
    Column1Search = InputBox("Col 1 Criteria: ")
    Set foundCellCol1 = Col1Rng.Find(What:=Column1Search)
    If Not foundCellCol1 Is Nothing Then foundCellCol1.Select Else: MsgBox "Search term not found!"
End Sub

您可以在另一个位置生成所有匹配项的列表吗?

Option Explicit
Sub FindingColumn()
    Dim Col1Rng As Range, Column1Search As String, foundCellCol1 As Range, lastRow As Long, lastFoundRow As Long
    lastRow = Range("A100000").End(xlUp).Row
    Set Col1Rng = ActiveSheet.Range("A1:A" & lastRow)
    Column1Search = InputBox("Col 1 Criteria: ")
    Set foundCellCol1 = Col1Rng.Find(What:="*" & Column1Search & "*")
    While Not foundCellCol1 Is Nothing
        If Not foundCellCol1 Is Nothing Then
            Range("B" & Range("B100000").End(xlUp).Row + 1) = foundCellCol1.Value
            Set Col1Rng = ActiveSheet.Range("A" & foundCellCol1.Row & ":A" & lastRow)
            lastFoundRow = foundCellCol1.Row
            Set foundCellCol1 = Col1Rng.Find(What:="*" & Column1Search & "*")
            If foundCellCol1.Row = lastFoundRow Then Set foundCellCol1 = Nothing
        End If
        DoEvents
    Wend
End Sub