我正在尝试创建一个函数来根据插入的匹配字符串获取单元格的列号。如果在第一行找到两个匹配项,我想返回最后一个匹配项。例如,“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/