【问题标题】:VBA (Upper) Type Mismatch ErrorVBA(上)类型不匹配错误
【发布时间】:2017-04-14 19:12:51
【问题描述】:

我正在运行一些 VBA 来将整个 Excel 工作表切换为大写。

但是它会跳闸并给出类型不匹配错误并在中途失败。

Sub MyUpperCase()

    Application.ScreenUpdating = False

    Dim cell As Range
    For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
        If Len(cell) > 0 Then cell = UCase(cell)
    Next cell

    Application.ScreenUpdating = True


End Sub

我假设它在特定单元格上绊倒,但是有数百行。有没有办法让它跳过错误

【问题讨论】:

  • If Len(CStr(cell)) > 0 Then cell = UCase(CStr(cell)) 有帮助吗?
  • 您的单元格中可能存在错误 - 您是否尝试过调试代码以查看导致错误的行?简单地忽略错误是不好的做法。
  • 数字也可能搞砸了。基本的错误处理应该可以解决这个问题:)

标签: vba excel


【解决方案1】:

如果您想将所有单元格转换为大写文本(包括公式)

Sub MyUpperCase()
    Application.ScreenUpdating = False
        Dim cell As Range, v As String

        For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
            v = cell.Text
            If Len(v) > 0 Then cell.Value = UCase(v)
        Next cell
    Application.ScreenUpdating = True
End Sub

请注意,所有不返回 Null 的公式也将被转换为文本。

【讨论】:

  • 完美,在#N/A 处倒下,但文件没有任何公式。谢谢。
【解决方案2】:

要查看问题所在的单元格(或多个单元格),您可以尝试:

On Error Resume Next 'to enable in-line error-catching
    For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
        If Len(cell) > 0 Then cell = UCase(cell)
        If Err.Number > 0 Then
            Debug.Print cell.Address
            Err.Clear
        End If
    Next cell
On Error GoTo 0 'Turn off On Error Resume Next

On Error Resume Next 经常被滥用,尤其是新的 VBA 程序员。不要在 sub 开头打开它,永远不要关闭它,永远不要检查Err.Number。我发现认为它具有特定范围是一个非常好的主意,并通过缩进其中的语句来强调该范围,就像我在上面所做的那样。 @MacroMan 提出了一个很好的观点,即不应简单地忽略错误(如果您滥用此构造,就会发生这种情况)。

【讨论】:

    【解决方案3】:

    在代码中间添加以下错误捕获:

    On Error Resume Next
    If Len(cell) > 0 Then cell = UCase(cell)
    
    If Err.Number <> 0 Then
        MsgBox "Cell " & cell.Address & " has an error !"
    End If
    On Error GoTo 0
    

    注意:您的代码可以使用数值,但在运行原始代码时,#NA#DIV/0 会引发错误。

    【讨论】:

      猜你喜欢
      • 2012-02-25
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      相关资源
      最近更新 更多