excel vba类型不匹配 - 比较值w /“right”,“offset”,“len”的组合

时间:2017-05-26 13:13:15

标签: excel vba excel-vba compare

为什么以下可能会返回类型不匹配错误?

Dim Arrow As Workbook
If wb.Name Like "*Arrow*" Then
Set Arrow = wb
dplastrow = activeworkbook.Worksheets(1).UsedRange.Rows(Worksheets(1).UsedRange.Rows.Count).Row
LastArrow = Arrow.ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row

For Each account In activeworkbook.Worksheets(1).Range("D11:D" & dplastrow)
For x = 2 To LastArrow
If (Trim(Right(account.Offset(0, 1), Len(account.Offset(0, 1) - 2))) = Arrow.Worksheets(1).Cells(x, "BL")) Then
'some action

我能够vlookup并在实际的excel gui中返回它的匹配值没问题。我尝试用cstr(,val(和/或用.text附加它们)来封装单元格无效。

1 个答案:

答案 0 :(得分:0)

如果要随意从一个单元格向右移取值的长度,则需要确保有足够的文本从长度中减去2。

Dim Arrow As Workbook
If wb.Name Like "*Arrow*" Then
    Set Arrow = wb
    With wb.Worksheets(1)
        lastArrow = .cells(.rows.count, "BL").end(xlup).Row
    End With

    dplastrow = ActiveWorkbook.Worksheets(1).UsedRange.Rows(Worksheets(1).UsedRange.Rows.Count).Row

    For Each account In ActiveWorkbook.Worksheets(1).Range("D11:D" & dplastrow)
        For x = 2 To lastArrow
            If Len(account.Offset(0, 1)) > 2 Then
                If (Trim(Right(account.Offset(0, 1), Len(account.Offset(0, 1) - 2))) = _
                    Arrow.Worksheets(1).Cells(x, "BL")) Then
                    'some action
                End If
            End If
        Next x
    Next account
End If

您应该远离依赖ActiveSheet获取工作表引用(请参阅How to avoid using Select in Excel VBA macros),并且有更好的方法来确定Arrow列BL中的最后一行。