首页 > 解决方案 > 使用excel VBA查找包含数值的单元格的列号

问题描述

在我的 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

*

标签: excelvba

解决方案


试试这个。使用时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

推荐阅读