使用循环结束/如果溢出代码有麻烦

时间:2019-07-15 19:39:44

标签: excel vba

每次尝试结束if语句时,我都会收到一条错误消息“如果没有块if,则结束”,但是每次我收到错误消息“ overflow”时,都将结束。

我尝试取出g = g + 1,但是我需要这样做才能使代码正确运行,并且我尝试编写没有循环的代码,但这很长,因为我需要代码来运行多个不同的循环变量。

Sub Pleasepleasework()    
    Dim i As Integer
    Dim g As Integer

    Dim Media As Object
    Dim BOM As Object

    i = 4
    g = 6

    Set Media = Worksheets("Media").Cells(i, 1)
    Set BOM = Worksheets("Bill of Materials").Cells(g, 6)

    Do Until i = 17 And g = 23
        i = i + 1
        g = g + 1

        If Media.Value = 0 Then BOM.ClearContents
    Loop
End Sub

我希望这段代码遍历单元格,并在第一列中识别它们是否为零。如果值为零,我希望它跳转到BOM表并清除g行第6列中的内容。

1 个答案:

答案 0 :(得分:2)

我认为以下代码或多或少是您要实现的目标:

Option Explicit

Sub Pleasepleasework()

Dim i As Long, g As Long
Dim MediaSht As Worksheet, BOMSht As Worksheet

' set the worksheet objects
Set MediaSht = ThisWorkbook.Worksheets("Media")
Set BOMSht = ThisWorkbook.Worksheets("Bill of Materials")

g = 6
With MediaSht
    For i = 4 To 17
        If .Range("A" & i).Value = 0 Then
            BOMSht.Range("G" & g).ClearContents
        End If
        g = g + 1
    Next i
End With


End Sub