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

时间:2014-01-18 23:51:34

标签: excel vba excel-vba

我试图在我的excel工作簿(.vba)中的命名区域中找到匹配的单元格值。我知道我正在寻找的价值,并且知道范围的名称,当我第一次运行代码时没有问题,但是在第二次运行时使用新的范围名称,我得到一个错误。

我尝试了几种不同的搜索命名范围的方法,两种方式都会产生相同的错误。错误是:“对象'_Global'的方法'范围'失败”。

我尝试的初始代码是:

'march through the list of racks
For i = iFirstRackRow To iLastRackRow
    iCurrRackSize = Sheets("PLC I-O").Cells(i, 6).value
    iHardwareIndexEnd = iHardwareIndex + iCurrRackSize - 1
    rngCardsName = Trim(Sheets("PLC I-O").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 I-O").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 I-O").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

我不确定我在这里做错了什么。请帮忙。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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