从所有单元格中删除指定的值而不破坏文档格式

时间:2014-12-13 18:45:27

标签: excel-vba formatting cell vba excel

我需要从指定的单元格中删除一组指定的数字,而不会丢失实际的文档格式。这组数字包含100个数字,但为了简单起见,我只展示了几个字符。

我已经尝试了对象ClearContents的方法Range,但我得到了“运行时错误1004”。我该如何解决这个问题?

Sub deleteval()

Dim delete
delete = Array("1", "2", "3", "4", "5", "a", "b", "c", "d", "e", "f", "g")

Dim i As Long, j As Long

Dim isThere As Boolean

For i = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
    For j = LBound(delete) To UBound(delete)
        If StrComp(Range("A" & i), delete(j), vbTextCompare) = 0 Then
            isThere = True
        End If
    Next j
    If isThere Then
        ActiveSheet.Range("A" & i).delete shift:=xlUp
    End If
    isThere = False
Next i

End Sub

1 个答案:

答案 0 :(得分:0)

试试这个,干什么工作

ActiveSheet.Range("A" & i).Select
Selection.ClearContents

一些提示: 录制一个宏,同步你的动作,停止宏录制,然后看到自动生成的代码。

对此进行了测试,并且清晰的内容按预期工作! (添加了错误处理)

Sub deleteval()
On Error GoTo errdeleteval
Dim delete
delete = Array("1", "2", "3", "4", "5", "a", "b", "c", "d", "e", "f", "g")

Dim i As Long, j As Long

Dim isThere As Boolean

For i = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
    For j = LBound(delete) To UBound(delete)
        If StrComp(Range("A" & i), delete(j), vbTextCompare) = 0 Then
            isThere = True
        End If
    Next j
    If isThere Then
        ActiveSheet.Range("A9" & i).ClearContents
    End If
    isThere = False
Next i

On Error GoTo 0
Exit Sub
errdeleteval:
Debug.Print Err.Description & " (A" & i & ") "

End Sub