【问题标题】:Find column number of cell containing numeric value using excel VBA使用excel VBA查找包含数值的单元格的列号
【发布时间】:2020-04-01 00:24:45
【问题描述】:

在我的excel表格中,单元格A1的值为1000,而单元格B1的值为10000。

我正在尝试查找列号。包含“1000”的单元格。

列号我想要的输出是 1(即单元格 A1),但我得到的输出为 2,代码如下(指单元格 B1 中的值 10000)。另一方面,在单元格 B1 中,如果我将 10000 替换为 10100,则会得到以下代码的输出为 1。

我可以知道我需要对代码进行哪些更改才能获得所需的输出吗?

*

Sub Find_Number()
Dim Find As Range
Set Find = Range(Cells(1, 1), Cells(1, 5)).Find("1000")
Debug.Print Find.Column
End Sub

*

【问题讨论】:

  • 指定Range.Find的其他参数:AfterLookInLookAt等。之后应该是最后一个单元格。
  • 如果你想准确找到 1000,那么Application.Match 是另一种选择。
  • LookIn:= xlWhole。我会将Find 重命名为Found 以避免使用关键字作为变量。还可以使这些陈述直观:If Not Found is Nothing Then Debug.Print Found.Column
  • 谢谢@BigBen
  • 感谢@urdearboy 的宝贵帮助和建议。总结是我必须使用 LookAt:=xlWhole 如果我使用 Range.Find 或者更好地使用 Application.Match

标签: excel vba


【解决方案1】:

试试这个。使用Find 时始终建议指定参数,因为它们可能有意外的设置。通过将after 指定为范围中的最后一个单元格,搜索将从第一个单元格开始,而不是跳过它。

并在继续操作之前检查您是否发现了一些错误。

另一种方法是使用Match,它可以在一维范围内正常工作。

(我也不喜欢使用Find作为变量名,即使它被允许。)

Sub Find_Number()

Dim rFind As Range

With Range(Cells(1, 1), Cells(1, 5))
    Set rFind = .Find(what:=1000, after:=.Cells(.Cells.Count), LookAt:=xlPart, _
                     SearchDirection:=xlNext, MatchCase:=False) 'might want to specify whole rather than part
    If Not rFind Is Nothing Then Debug.Print rFind.Column 'avoid error if not found
End With

'alternative
'Dim v As Variant

'v = Application.Match(1000, Range(Cells(1, 1), Cells(1, 5)), 0)
'If IsNumeric(v) Then Debug.Print v

End Sub

【讨论】:

  • 非常感谢您。只需一个查询。 10000 里面有 1000,这就是为什么我得到错误的列号。作为输出,因为我没有提到其他参数。那么我是否应该提到 LookAt:=xlWhole 以完全匹配我的搜索? (替代答案也很棒。非常感谢。)
  • 是的,就是这样。
  • 注意到您不使用 Find 作为变量名的建议。再次感谢您的支持。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-12
  • 2022-01-11
相关资源
最近更新 更多