使用for循环和if语句清除单元格的内容

时间:2021-02-21 19:55:27

I have this bit of code:

我有这段代码:

For Each cell In Worksheets("Sheet1").UsedRange
      If(Left(cell, 3) <> 574 Or Left(cell, 3) <> 584 Or Left(cell, 3) <> 233) Then cell.ClearContents
Next

The codes purpuse is to loop through all used cells in the spread sheet and if the first three digits are not 574, 233, 584, then the cell will be set to empty.

代码purpuse是遍历电子表格中所有使用过的单元格,如果前三个数字不是574,233,584,那么单元格将被设置为空。

In my spreadsheet I have values that should pass, the first three digits are equal to 574, 233, 584; but instead the loop delete everything from the spreadsheet. Any insight into errors in logic I may have would be welcomed.

在我的电子表格中,我有值应该通过,前三位数等于574,233,584;但相反,循环删除电子表格中的所有内容。任何洞察我可能有的逻辑错误都会受到欢迎。

1 个解决方案

#1


3  

Whenever I see multiple conditions for IF statement, I immediately think about using Select Case for ease of readability and maintenance.

每当我看到IF语句的多个条件时,我立即考虑使用Select Case以便于阅读和维护。

For Each cell In Worksheets("Sheet1").UsedRange

    Select Case Left(cell,3)

        Case Is = 574, 584, 233 'do nothing
        Case Else: cell.ClearContents

    End Select

Next

#1


3  

Whenever I see multiple conditions for IF statement, I immediately think about using Select Case for ease of readability and maintenance.

每当我看到IF语句的多个条件时,我立即考虑使用Select Case以便于阅读和维护。

For Each cell In Worksheets("Sheet1").UsedRange

    Select Case Left(cell,3)

        Case Is = 574, 584, 233 'do nothing
        Case Else: cell.ClearContents

    End Select

Next