获取第一行匹配string的列号。 Excel VBA

我试图创build一个函数来获取基于匹配的string被插入的单元格的列号。 如果在第一排中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对象找不到列号的下一个。

试试这个,让我知道。

私人函数GetColumnNumber(strKeyword作为string)作为整数

  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 

结束function

我使用了一种不同的方法,通过改变search方向,您可以使用单个查找方法find最后一个实例。

私人函数GetColumnNumber(名称作为string)作为整数

 Dim res As Object Set res = Sheets("Unified").Cells(1, 1).EntireRow.Find(What:=name _ , LookIn:=xlValues _ , LookAt:=xlPart _ , SearchOrder:=xlByColumns _ , SearchDirection:=xlPrevious _ , MatchCase:=False) If res Is Nothing Then GetColumnNumber = 0 Else GetColumnNumber = res.Column End If 

结束function

我已经创build了另一个方法来添加在这个function。 这是工作顺便说一句…我使用Variant数组来获取列号。

 Private Function GetColumnNumber(name As String) As Integer Dim play As Variant, j As Long, Current As Integer Set play = Sheets("Unified").Range("1:1") For i = 1 To play.Columns.Count If InStr(play(1, i), name) > 0 Then Current = i End If Next i GetColumnNumberArray = Current End Function 

我看看这篇文章,这对优化你的代码是非常有帮助的。 http://fastexcel.wordpress.com/2011/10/26/match-vs-find-vs-variant-array-vba-performance-shootout/显然,查找和匹配的使用对于您的计算机来说是非常苛刻的命令&#x3002;