使用循环清除内容

时间:2018-01-24 04:09:09

标签: excel vba excel-vba

我已经编写了以下代码来检查A行中的值是否等于"预测"然后Range D5:D53应清除其内容。

第1行是一个vlookup,因此有一个公式可以推导出" Actual"或"预测"

Dim k As Integer

For k = 1 To 13
    If Sheets("2017 Forecast").Cells(k, 1).Value = "Forecast" Then
        Sheets("2017 Forecast").Range("D5:D53").Select.ClearContents
    End If
Next k

2 个答案:

答案 0 :(得分:1)

在使用Select之前无需使用ClearContents

此外,请尝试添加UCase以确保您的文字中间没有任何大写字母。

<强>代码

Dim k As Integer

With ThisWorkbook.Sheets("2017 Forecast")
    For k = 1 To 13
        If UCase(.Cells(k, 1).Value2) = "FORECAST" Then
            .Range("D5:D53").ClearContents
        End If
    Next k
End With

答案 1 :(得分:0)

也许这适合你?

Option explicit

Sub Compare skies()

Dim k As long
Dim ValueRead as variant

With Sheets("2017 Forecast")
For k = 1 To 13

ValueRead = .Cells(k, 1).Value

' Slow, case insensitive string comparison '
If strcomp(ValueRead,"Forecast",vbtextcompare) = 0 Then
    .Range("D5:D53").ClearContents ' You want to clear the exact same range 13 times? '
Elseif strcomp(ValueRead,"Actual",vbtextcompare) <> 0 then
Msgbox("VLOOKUP returned a value outside of Actual and Forecast")

End if

Next k
End with

End sub