Excel / VBA – 函数返回整数
我想要一个函数返回给定rowIndex和一个单元格的列的索引:
'Get index of column given a heading name Function FindColumnIndex(name As String, rowNumber As Integer) As Integer Dim index As Integer index = 1 Dim found As Boolean found = False Do While found = False If Cells(rowNumber, index).Value = name Then FindColumnIndex = index Exit Do End If index = index + 1 Loop FindColumnIndex = index End Function
然后我将把它赋值给一个值:
Dim colIndex As Integer colIndex = FindColumnIndex("Physical or Virtual", 2)
问题是这不工作 – 我相信我的function是不正确的 – 任何人知道我在做什么错了?
有一件事我发现了蝙蝠:
If Cells(row, index).Value = name Then
传递给函数的variables被命名为rowNumber
,而不是row
。 将该行更改为:
If Cells(rowNumber, index).Value = name Then
编辑:
还有一点需要注意的是,你的function从来没有真正停止。 它唯一的原因是因为它试图读取列16385(因为Excel限于16384列*),它会立即杀死函数,返回一个#VALUE
错误,运行到应用程序定义的错误。
下面的版本可以防止这种情况发生,如果没有find请求的列名,则返回-1。
Option Explicit Function FindColumnIndex(name As String, rowNumber As Integer) As Integer Dim index As Integer index = 1 Dim found As Boolean found = False FindColumnIndex = -1 Do While found = False If Cells(rowNumber, index).Value = name Then FindColumnIndex = index found = True End If index = index + 1 If index > 16384 Then Exit Do Loop End Function
无论如何,Excel 2007是有限的。 我不知道新版本是否有更大的限制。]
If Cells(row, index).Value = name Then
你的意思是:
If Cells(rowNumber , index).Value = name Then
无论如何,有这样做的function,像MATCH ,INDEX&Co.