【问题标题】:excel vba type mismatch- comparing values w/ combination of "right", "offset", "len"excel vba 类型不匹配 - 比较带有“right”、“offset”、“len”组合的值
【发布时间】:2017-05-26 13:13:14
【问题描述】:

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

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

我能够在实际的 excel gui 中查找并返回它的匹配值,这没问题。我尝试将单元格封装在 cstr(, val( 和/或用 .text 附加它们无济于事。

【问题讨论】:

  • 下一列是否有一个空白单元格(或长度小于 3 的文本))将 -2 的 len 返回给 Right 函数?
  • 或者任何单元格中有错误?
  • LastArrow = Arrow.ActiveSheet.UsedRange.Rows(**Arrow.**ActiveSheet.UsedRange.Rows.Count).Row
  • 您说得对,先生,谢谢!关于长度的单元格的存在
  • 是的,我的长度也

标签: vba excel compare


【解决方案1】:

如果要从右边一个单元格中任意取值的长度,则需要确保有足够的文本从长度中减去 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),并且有更好的方法来确定箭头列 BL 中的最后一行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2015-04-28
    相关资源
    最近更新 更多