excel - 使用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
*
解决方案
试试这个。使用时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
推荐阅读
- javascript - 在使用 parseInt 时,他们有什么办法可以**不能**四舍五入?
- sql-server - VS2019 MVC 数据库解决方案无法在第二台机器上运行
- java - 在thymeleaf和spring boot控制器中使用复选框处理多行提交
- angular - 我想获取元素
这样我就可以设置自定义 aria-label 属性,但 HTMLCollection 返回空 - javascript - 当函数返回 null 时会发生什么?
- java - 如何从使用 POI 的 Excel 模板中读取合并区域的边界信息?
- eclipse - 在执行期间在eclipse中自动传递输入参数
- kotlin - 星型注释
- r - 在绘图之外添加组符号
- javascript - Redux RTK Query:仅使列表中的单个元素无效