从单元格中删除内容,IFIsNumeric = False

所以我有这个程序; 从远程系统扫描值。 有时它可以超时,如果networking宕机,它会把#nan错误或类似的东西。

当我尝试将该错误消息写入数据库时​​; 由于它正在寻找一个数值,所以会出错“数据types不匹配”。

为了解决这个问题,我决定尝试清理结果。 所以我有下面的代码。 它大部分时间工作; 我看到它失败的是,如果有一个数字中途通过,然后再次错误。 一旦它达到数字的数字,它似乎像停止循环,并没有清除其他任何东西。

任何人可以帮助我的东西都会很棒。 也许我正在做这个不好的方法。 我试图给我的例子下面我想看看。 如果您有任何build议或疑问,请让我知道。

Private Sub Clean() 'Select Current Row For where to start cleaning. LoopIndex is a global variable. 'Just giving the line of where to read from so I do not need to read the whole sheet. Range("B" & LoopIndex).Select 'Start the loop, to go through the entire row. Do Until IsEmpty(ActiveCell) 'Checks if it is a number value; if it is not it will clear out the data. If IsNumeric(ActiveCell.Value) = False Then ActiveCell.Value = "" End If ActiveCell.Offset(0, 1).Select Loop End Sub 

它看起来像什么

 |A |B |C |D | |#error|#Error|3 |#Error| 

我想要它看起来像。

 |A |B |C |D | | | |3 | | 

它在做什么。

 |A |B |C |D | | | |3 |#Error| 

尝试这个

 Sub RemoveErrors(TheRange As Range) Dim c For Each c In TheRange If IsError(c) Then c.Value = "" Next c End Sub 

编辑:没有循环的版本,可能会加快一点,如果他们是公式错误

 Sub RemoveErrors(TheRange As Range) On Error Resume Next TheRange.SpecialCells(xlCellTypeFormulas, xlErrors).Value = vbNullString On Error GoTo 0 End Sub 

像这样使用它:

 Sub Test() RemoveErrors Range("A1:D21") End Sub 

如果你喜欢使用IsNumeric函数,那么使用这个:

 Sub RemoveNAN(TheRange As Range) Dim c For Each c In TheRange If IsNumeric(c) = False Then c.Value = "" Next c End Sub 

我是这样做的,因为variables范围在不同的工作表上。 我只是发布这个给未来的解决scheme。

感谢大家的帮助。

  Private Sub Clean() Dim StartRow As String Dim LastCol As Long Dim EndRow As String Dim StartCol As String Dim MyCol As String StartCol = "B" With ActiveSheet LastCol = .Cells(LoopIndex, .Columns.Count).End(xlToLeft).Column End With MyCol = GetColumnLetter(LastCol) RemoveErrors Range(StartCol & LoopIndex & ":" & MyCol & LoopIndex) End Sub 'Does the replacing Sub RemoveErrors(TheRange As Range) Dim c For Each c In TheRange If IsError(c) Then c.Value = "" Next c End Sub 'Gets the Column Letter Function GetColumnLetter(colNum As Long) As String Dim vArr vArr = Split(Cells(1, colNum).Address(True, False), "$") GetColumnLetter = vArr(0) End Function