在命名范围中查找匹配的单元格值

我正在尝试在我的Excel工作簿(.vba)中的命名范围中查找匹配的单元格值。 我知道我正在寻找的价值,也知道范围的名称,当我运行代码第一次运行没有问题,但第二次运行一个新的范围名称,我得到一个错误。

我已经尝试了几种不同的方式来search命名的范围,并且两种方式导致相同的错误。 错误是:“_Global”对象的“方法范围”失败。

我尝试的最初代码是:

'march through the list of racks For i = iFirstRackRow To iLastRackRow iCurrRackSize = Sheets("PLC IO").Cells(i, 6).value iHardwareIndexEnd = iHardwareIndex + iCurrRackSize - 1 rngCardsName = Trim(Sheets("PLC IO").Cells(i, 2).value & "Cards") 'march through the rack hardware For j = iHardwareIndex To iHardwareIndexEnd modCardSize = 0 'march through each card in the rack For Each zCell In Range(rngCardsName) If zCell = Sheets("PLC IO").Cells(j, 2) Then modCardSize = Sheets("Links").Cells(zCell.Row, zCell.Column + 1).value Exit For End If Next zCell If modCardSize <> 0 Then 'io module matched NumRows = NumRows + modCardSize Else 'processor or adapter module found NumRows = NumRows + 1 End If Next iHardwareIndex = iHardwareIndex + iCurrRackSize Next 

或者我也试过:

 Dim rngFoundCell As Range With Range(rngCardsName) Set rngFoundCell = .Find(What:=Sheets("PLC IO").Cells(j, 2).value, _ After:=.Cells(.Cells.Count), _ LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False) If Not rngFoundCell Is Nothing Then 'cell match was found rngrow = rngFoundCell.Row rngcol = rngFoundCell.Column modCardSize = Sheets("Links").Cells(rngrow, rngcol + 1).value Else 'cell match was not found End If End With 

我不知道我在这里做错了什么。 请帮忙。

我认为问题是你的.FindAfter:=参数。 尝试使用值After:=.Cells(1)更改参数。

感谢大家! 我发现这个问题。 这是修剪指令。 由于表单中有多个空格(“PLC IO”)。单元格(i,2).value,我需要使用一个自定义函数来确保所有的空格被删除。