错误9下标超出范围尝试了一切

Set finder = .Find(clientName, LookIn:=xlValue, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext)行接收到一个运行时错误9下标超出范围,我试了一堆事情来解决它。 我错过了一些至关重要的东西,我不确定它是什么。 通读这里的所有其他post,似乎没有帮助/关联太密切。

注意事项: 1)variablesclientName是一个标准的string,在传入函数时被正确赋值。 2)我通过在查找行之前添加contactsMaster.Activate行来testing工作表对象,并且它正确地激活了表单,这导致我相信它与表单或工作簿的名称无关(我使用getBook = Activeworkbook.Name在主要sub为了避免与用户名称更改的问题3)我已经将范围更改为contactsMaster.Range("A:C") ,并没有改变任何东西。 4)数据存储在列A到C中。每个单元一个客户端名称。 这个函数旨在通过客户端名称来标准化命名约定方法,以便我可以使用相同的约定从任何macros中find文件。 5)最初我以为在错误行上使用.Address是由于某种原因抛出一个错误,但它似乎不是这样,因为我已经删除它,仍然收到相同的错误。 代码如下:

 Function GetClientName(clientName As String) As String 'Gets specific client name to save excel file in a standardized format to be found easily 'Sets Objects/vars Dim finder As Range Dim location As Long Dim contactsMaster As Worksheet Set contactsMaster = Workbooks("EEB MACRO DEVELOPMENT BOOK").Sheets("Contacts Master") With contactsMaster.Range("A1:C1000") Set finder = .Find(clientName, LookIn:=xlValue, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext) End With 'Prevents error for not finding client in contacts master If finder Is Nothing Then GoTo endFunc End If location = finder.Row GetClientName = contactsMaster.Cells(location, 1) Exit Function endFunc: GetClientName = clientName End Function 

你只需要使LookIn:=xlValues ,最后注意“S”。 另外,你正在使用Lookin:=LookAt:= ,所以为了保持连续性,我build议在开始时加上What:= ,所以你得到:

Set finder = .Find(What:=clientName, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext)