条件If语句将单元格设置为0

时间:2013-07-10 22:10:55

标签: excel-vba vba excel

我有一个超过6000行和300列的电子表格。我需要知道如何在vba中编写代码,允许我读取列中的单元格,如果说“no”,则将其右边的3个单元格设置为等于零。调试时没有错误,但错误在cell.Offset行中。想法?

提前谢谢

Sub Macro1()

Dim rng As Range
Dim cell As Object

 With Sheets("Sheet1")
    Set rng = .Range("C1:C6000")
    For Each cell In rng
        If cell.Value = "no" Then
            cell.Offset(0, 1).Value = 0
            Exit For
        End If
    Next
 End With
End Sub

2 个答案:

答案 0 :(得分:0)

以下代码应该完成这项工作。使用For / Next循环,它将Sheet 1中的每个单元格从A1读取到A列中具有数据的最后一个单元格。如果当前单元格的值为“no”,则它将单元格的值设置为右侧三列,为值0。

    Sub SetTo0IfNo()
        Dim rng As Range
        Dim lastRow As Long
        Dim cell As Variant
        Application.Calculation = xlCalculationManual
        Application.ScreenUpdating = False
        With Sheets("Sheet1")
            lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
            Set rng = .Range("A1:A" & lastRow)
            For Each cell In rng
                If cell.Value = "no" Then
                    cell.Offset(0, 3).Value = 0
                End If
            Next
        End With
        Application.ScreenUpdating = True
        Application.Calculation = xlCalculationAutomatic
    End Sub

要将列A单元格右侧的单元格范围设置为0,您将使用仍然依赖于偏移函数的稍微不同的语法。例如,要将三个单元格立即设置为0,请使用以下代码替换上面的代码行cell.Offset(0,3).Value = 0

Range(cell.Offset(0, 1), cell.Offset(0, 3)).Value = 0

这种方法是必要的,因为与可以返​​回对一系列单元格的引用的工作表OFFSET函数不同,VBA OFFSET只能引用单个单元格。

答案 1 :(得分:0)

借用chuff的代码:

Sub SetTo0IfNo()
    Dim rng As Range
    Dim lastRow As Long
    Dim cell As Range

    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
        Set rng = .Range("A1:A" & lastRow)
        For Each cell In rng
            If cell.Value = "no" Then
                'cell.Offset(0, 3).Value = 0
                cell.Range("B1:D1").Value = 0
            End If
        Next
    End With
End Sub