如何使用VBA清除特定单元格

时间:2017-01-14 13:56:00

标签: vba

如果有人可以提供帮助,我无法完成代码的最后一部分。当一个单元格不是数字时,我需要它来删除单元格中的数据。

2 个答案:

答案 0 :(得分:0)

尝试以下代码:

Sub ValueOnly()

Dim x As Integer
Application.ScreenUpdating = False

With Sheets("Consolidated Data")
    For x = 1 To 3107

        With .Cells(10 + x, 9)
            If Not IsNumeric(.Value) Then .ClearContents
        End With

        With .Cells(10 + x, 10)
            If Not IsNumeric(.Value) Then .ClearContents
        End With

    Next x
End With

End Sub

答案 1 :(得分:0)

由于IsNumeric()可能存在问题,您可能需要尝试SpecialCells()方法,这有点棘手:

Option Explicit

Sub ValueOnly()
    Dim numericRng As Range, lastNumericRng As Range, lastRng As Range
    Dim iArea As Long

    With Sheets("Consolidated Data").Range("I11:I3317").SpecialCells(xlCellTypeConstants) '<--| consider only your wanted range "not blank" values
        Set numericRng = .SpecialCells(xlCellTypeConstants, xlNumbers) '<--| store "numeric" values

        If Intersect(.Cells(1), numericRng) Is Nothing Then '<--| check if first value is not numeric
            .Parent.Range(.Cells(1), numericRng(1).Offset(-1)).ClearContents
        End If

        With numericRng
            For iArea = 2 To .areas.Count '<--| clear all not numeric values between numeric ones
                .Parent.Range(.areas(iArea - 1).Offset(.areas(iArea - 1).Count).Resize(1), _
                              .areas(iArea).Resize(1).Offset(-1)).ClearContents
            Next
        End With

        Set lastRng = .areas(.areas.Count).Cells(.areas(.areas.Count).Count)
        If Intersect(lastRng, numericRng) Is Nothing Then '<--| check if last value is not numeric
            With numericRng
                Set lastNumericRng = .areas(.areas.Count).Offset(.areas(.areas.Count).Count).Resize(1)
            End With
            .Parent.Range(lastNumericRng, lastRng).ClearContents
        End If
    End With
End Sub