如何在第1行搜索条件,然后选择满足条件单元格的列?

问题描述 投票:0回答:1

我在上一个问题中没有得到太多帮助,但我认为这是因为我一次要求太多。因此,当我编码时,我将其分解为多个步骤,当我遇到问题时,我想我可以在这里提问。

因此,在该过程的这一步中,我尝试在第 1 行(始终是第 1 行)中搜索单元格内保存的特定条件。该条件在单元格中的前后都有值,因此我使用通配符“在此处插入条件”,以便它可以找到它。然后我希望它选择在其中找到此条件的列。例如 _1.D 始终位于第 1 列中。所以我希望它在 A1 中找到它,然后选择 A 列。

我认为我最终解决了所有错误,并且它实际上运行了,但是当我去运行它时,它不是只选择一列,而是选择所有错误。

下面是我正在使用的代码。 1-3000的值是任意的。我可能可以把它删掉,但我想给它尽可能多的空间,因为数据集大小各不相同,所以它可能在第 100 列结束,也可能在 2000 列结束。

此外:下一步基本上是将确定的列设置为新范围,然后在该范围中搜索第二个条件,因此它必须与能够做到这一点兼容。

Function WorksheetExists(WSName As String) As Boolean
    On Error Resume Next
    WorksheetExists = Worksheets(WSName).Name = WSName
    On Error GoTo 0
End Function
Sub FindData()

Dim shname As String
Dim rs As Worksheet
Dim SampleEnding As Variant

Do Until WorksheetExists(shname)
shname = InputBox("Enter sheet name")

If StrPtr(shname) = 0 Then
MsgBox ("User Cancelled!")
Exit Sub

Else
If Not WorksheetExists(shname) Then MsgBox shname & " doesn't exist!", vbExclamation

End If

Loop

SampleEnding = Application.InputBox("Select Sample ending string (_1.d, _2.d, etc.)", Type:=2)

If Sheets(shname).Cells(1, 3000).Value = SampleEnding Then Columns.Select
excel vba
1个回答
0
投票

这就是您在第 1 行查找内容所需的内容。

Sub FindInRowOne()
    Dim rFind As Range, sFind As String, fSheet As String, cFind As String
    Dim ws As Worksheet
    Dim wk As Workbook
    Set wk = ThisWorkbook
    fSheet = InputBox("Enter Sheet/Tab Name", "Which Tab to look on")
    sFind = InputBox("Enter text to find", "What to look for")
    Set rFind = wk.Sheets(fSheet).Rows("1:1").Find(What:=sFind, After:=wk.Sheets(fSheet).Range("XFD1"), LookIn:=xlValues, LookAt:=xlPart, _
        SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    If rFind Is Nothing Then
        MsgBox "Value Not Found" ''Debug Remove when done
    Else
        Debug.Print rFind.Column ''Column Number where value was found
        cFind = Split(wk.Sheets(fSheet).Cells(1, rFind.Column).Address(True, False), "$")(0)
        MsgBox "Value Found on Column: " & cFind ''Debug Remove when done
        wk.Sheets(fSheet).Columns(cFind).Select ''Not Recommended to use .Select in VBA
    End If
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.