【问题标题】:VBA Type mismatch, Run-time error 13VBA 类型不匹配,运行时错误 13
【发布时间】:2011-12-21 20:05:53
【问题描述】:

我刚刚写了一个小的 VBA 函数,如下所示。作为函数输出,我想得到 Range

Public Function selectRows(col As String) As Range

Dim begin, fini As Integer
Set TopCell = Cells(1, col)
Set BottomCell = Cells(Rows.Count, col)
If IsEmpty(TopCell) Then Set TopCell = TopCell.End(xlDown)
If IsEmpty(BottomCell) Then Set BottomCell = BottomCell.End(xlUp)
begin = TopCell.Row
fini = BottomCell.Row
Set selectRows = Activesheet.Range(col & begin & ":" & col & fini)
End Function

然后在尝试设置输出 =Range(...) 时出现类型不匹配错误

你能帮我解决这个问题吗,谢谢提前

【问题讨论】:

  • 函数返回值。但是你没有在这个函数中设置selectRows

标签: vba types range mismatch


【解决方案1】:

使用保留字(如 column)作为变量的名称是一个非常糟糕的主意。如果你想让函数返回一个范围,你需要:

Set selectRows = Range(scol & TopCell.Row & ":" & scol & BottomCell.Row)

而不是:

Set output = Range(column & TopCell.Row & ":" & column & BottomCell.Row)

还有其他问题,比如列是否为空。

【讨论】:

  • 嗨 Remou,很遗憾我仍然收到错误消息?该列不为空,我在列中有值
  • @Eva 我没有,一旦我替换了对 Column 的所有引用。添加断点(F9)并检查topcell和bottomcell的值。
  • 是的,我有 topcell 和 bottomcell 的值,但是以下命令会导致类型不匹配错误:Set selectRows = Range(....)
  • @Eva 如果您在工作表的范围前加上前缀会发生什么? Sheet1.range 还是 Activesheet.Range?
  • 我根据您的建议编辑了上面的代码,如您所见,但仍然无法将范围分配给 outp,我不明白;-)
【解决方案2】:

您输入的输入大于您拥有的列数。例如,我的 Excel 2003 有 IV 列,当我输入 IW 时,它会抛出 Error 13。如果您想清理代码,我将在下面留下我的代码。一些错误处理会有所帮助,这样就不会再发生这种情况了。

Public Function selectRows(ByVal sColumn As String) As Range

    Dim lColumn As Long
    Dim TopCell As Range, BottomCell As Range
    Dim wks As Worksheet

    Set wks = ActiveSheet

    lColumn = wks.Range(sColumn & "1").Column

    Set TopCell = wks.Cells(1, lColumn)
    Set BottomCell = wks.Cells(Rows.Count, lColumn)
    If IsEmpty(TopCell) Then Set TopCell = TopCell.End(xlDown)
    If IsEmpty(BottomCell) Then Set BottomCell = BottomCell.End(xlUp)
    Set selectRows = wks.Range(TopCell, BottomCell)

End Function

【讨论】:

    猜你喜欢
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多