【问题标题】:Found a cell with a particular value, how to reference that cell to search the entire column for another value找到具有特定值的单元格,如何引用该单元格以在整个列中搜索另一个值
【发布时间】:2019-05-31 17:14:23
【问题描述】:

我正在尝试在 excel 中编写一个程序,用户输入一个值,它会在其他工作表中搜索该值,找到具有该值的列,在该列的行中搜索晚于今天的日期,并返回值晚于今天日期的行的第 1 列的内容。

到目前为止,我已经能够找到具有输入值的单元格,但我不知道如何引用找到的单元格的列来搜索整个列的日期。

以下是我到目前为止的内容,我认为我应该在“If Worksheets(i).Cells(2, j).Value = Method Then”之后输入另一个 If 语句:“If Worksheets(i).Cells( ?, ?).Value >=Today() Then",但我不确定如何引用我想搜索的单元格,因为这些单元格取决于它们在上一个语句中的位置。

Private Sub CommandButton1_Click()

totalsheets = Worksheets.Count
Method = Worksheets("Search a Method").Cells(3, 6).Value

For i = 1 To totalsheets
    If Worksheets(i).Name <> "Search a Method" Then

    lastcolumn = Worksheets(i).Cells(2, Columns.Count).End(xlToLeft).Column

    For j = 2 To lastcolumn
        If Worksheets(i).Cells(2, j).Value = Method Then

        Worksheets("Search a Method").Activate

        lastrow = Worksheets("Search a Method").Cells(Rows.Count, 1).End(xlUp).Row
        Worksheets("Search a Method").Cells(lastrow + 1, 1).Value = Worksheets(i).Name

        End If
    Next
    End If
Next

End Sub

【问题讨论】:

  • 您可以使用.Column 捕获列,使用.Row 捕获找到的单元格的行。我可能会建议使用.Find() 使您的搜索更容易一些,因为您可以根据您的 If 语句和其他对单元格(2,j)或 .cells 的引用,在每张纸上使用范围“行(2)” (2,列数)

标签: excel vba


【解决方案1】:

将基于我关于使用.Find() 的建议,以下示例应该提供一些指导:

Dim findrng As Range, col As Long, method As String
method = "dog"
With Sheets(1)
    Set findrng = .Rows(2).Find(what:=method, LookIn:=xlValues, LookAt:=xlPart, searchorder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
End With
col = findrng.Column
Debug.Print col

我把“cat”放在cells(2,2)中,把“dog”放在cells(2,3)中,所以使用上面的代码,立即窗口显示为“3”,表示找到了method列.


以上图片:

【讨论】:

  • 您可以跳过 findrange 的使用,只使用 findcol where findcol = .Rows(2).Find(what:=method, LookIn:=xlValues, LookAt:=xlPart, searchorder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column) 作为上述的替代方案,尽管在我提供的代码中,您已经保存了范围,并且可以用所述范围做其他事情
  • @Marcucciboy2 这是 VBA 中的标准 IDE;我只是将编辑器格式颜色更改为我可以长时间盯着的颜色(工具 -> 选项)。
猜你喜欢
  • 2018-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多