Excel/VBA-返回整数的函数
我想要一个函数返回给定行索引和单元格值的列的索引:Excel/VBA-返回整数的函数,excel,vba,Excel,Vba,我想要一个函数返回给定行索引和单元格值的列的索引: '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 = Fals
'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)
问题是这不起作用——我确信我的功能是不正确的——有人知道我做错了什么吗?我一下子发现了一件事:
If Cells(row, index).Value = name Then
传递给函数的变量名为rowNumber
,而不是row
。将该行更改为:
If Cells(rowNumber, index).Value = name Then
编辑: 另一件需要注意的事情是,函数本身从未真正停止。它结束的唯一原因是,它在尝试读取列16385时遇到应用程序定义的错误(因为Excel限制为16384列*),这会立即终止函数,并返回一个
#值
错误
以下修订版阻止了该操作,如果未找到请求的列名,则返回-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
[*Excel2007因此受到限制。我不知道新版本是否有更大的限制。]
If Cells(row, index).Value = name Then
你是说:
If Cells(rowNumber , index).Value = name Then
无论如何,有一些函数可以做到这一点,比如INDEX&Co.您的参数被称为
rowNumber
,但是在循环中您使用row
时,您可以通过在模块顶部使用选项Explicit
来避免此类错误。您还可以在VBE中的“工具>选项>编辑器>要求变量声明”下将其设置为默认值。请参见:MATCH:Excel 2013仍具有相同的限制:1048576行和16384列