vba - 获取第一行匹配字符串的列号。 Excel VBA

标签 vba excel numbers find

我正在尝试创建一个函数来根据插入的匹配字符串获取单元格的列号。如果在第一行找到两个匹配项,我想返回最后一个匹配项。例如,“TotalSalary Jan”和“TotalSalary Feb”。将“TotalSalary”作为参数插入后,我将获得“TotalSalary Feb”的列号。我的代码:

Private Function GetColumnNumber(name As String) As Integer

Dim res As Object, ret As Integer

Set res = Sheets("Unified").Cells(1, 1).EntireRow.Find(What:=name, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)

If Not res Is Nothing Then
    ret = res.Column
    Do
        Set res = .FindNext(res)
        ret = res.Column
    Loop While Not res Is Nothing And res.Column <> ret
    GetColumnNumber = ret
End If

End Function

顺便说一句,代码无法正常工作。 res 对象找不到列号的下一个。

最佳答案

试试这个,让我知道。

私有(private)函数 GetColumnNumber(strKeyword As String) As Integer

    Dim rngColLoop      As Range
    Dim intCounter      As Integer
    Dim intColNum       As Integer
    Dim intPrevious     As Integer
    Dim intCurrent      As Integer

    lngCounter = 0
    With Sheets("Unified").Cells(1, 1).EntireRow
        For Each rngColLoop In .Columns
            If Trim(rngColLoop) <> "" Then
                If InStr(1, UCase(Trim(rngColLoop)), UCase(Trim(strKeyword))) > 0 Then
                    intCounter = intCounter + 1
                    If intCounter = 1 Then
                        intPrevious = rngColLoop.Column
                        intCurrent = rngColLoop.Column
                    Else
                        intPrevious = intCurrent
                        intCurrent = rngColLoop.Column
                    End If

                End If
            End If
        Next rngColLoop
    End With
    If intCounter = 0 Then
        GetColumnNumber = 0
    Else
        GetColumnNumber = intCurrent
    End If

    Set rngColLoop = Nothing

结束功能

关于vba - 获取第一行匹配字符串的列号。 Excel VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26352039/

相关文章:

excel - 重复值 n 次,其中 n 也可以是 0.5

java - 这是什么类型的号码?

php 2000 1000 到 9999 之间的唯一随机数

excel - 慢查找宏

excel - 循环遍历数字组合

excel - 在单个列或一系列列上运行宏

excel - 找到最后一行空的,插入图片(代码无法识别已经包含图像的单元格)

excel - 我如何只获取 future 日期而不是 future 和过去的日期?

vba - 在本地处理预期错误的模式,重新抛出意外错误

numbers - 使用 DCG 将 Prolog_Numbers 英语翻译成法语