2016-11-30 137 views
0

我正在运行一些VBA来将整个Excel工作表切换为大写。VBA(上)类型不匹配错误

但是,它跳过,并提供类型不匹配错误,并在一半通过失败。

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 

enter image description here

我假设它被绊倒在一个特定的细胞但有数百行。有没有办法让它跳过错误

+0

'如果Len(CStr(cell))> 0 Then cell = UCase(CStr(cell))'help's all? – bobajob

+5

你可能有一个错误的单元格 - 你有没有试过调试你的代码来查看哪条线路导致错误?简单地忽略错误就是不好的做法。 –

+0

数字可能会把它搞砸。基本的错误处理应该解决这个问题:) –

回答

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 

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

+0

完美,在#N/A时落空,但是该文件没有任何公式。谢谢。 – GPH

1

要了解细胞(或细胞)的问题,你可以尝试:

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编程。不要在子版本开始时打开它,并且永远不要关闭它,并且永远不要检查Err.Number。我认为这是一个非常好的主意,可以认为它具有特定的范围,并且通过缩小其中的陈述来强调范围,正如我上面所做的那样。 @MacroMan提出了一个很好的观点,即错误不应该被忽略(如果你滥用这个构造,会发生什么)。

0

添加下面的错误捕获在你的代码的中间:

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运行你原来的代码时有一个人要养错误。