VBA循环问题。仅适用于当前选项卡

时间:2015-02-18 05:27:49

标签: excel vba loops

我正在寻找一种在Excel中使用VBA循环遍历电子表格的方法。我发现很多网站都提供了使用范围功能的建议,但没有足够的具体解决我所遇到的问题。宏仅适用于当前选项卡。它不会循环。

Sub UpdateAll()
'
' UpdateAll Macro
'

Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets

Call Update_OI

Next ws

End Sub



Sub Update_OI()
'
' Update_OI Macro

Dim rng As Range


For Colx = 3 To 81

    Cells(10, Colx).Select


  If ActiveCell.Offset(-8, 0) = "X" Then GoTo 4

  If ActiveCell.Offset(-3, 0) = 0 Then GoTo 4

  If ActiveCell.Value = vbNullString Then GoTo 4

  If ActiveCell.Value <> vbNullString Then GoTo 1


1
    goalvalue = Cells(70, Colx).Value
    Range(Cells(69, Colx), Cells(69, Colx)).GoalSeek Goal:=goalvalue, ChangingCell:=Range(Cells(10, Colx), Cells(10, Colx))


4
Next Colx

End Sub

3 个答案:

答案 0 :(得分:1)

您可以将工作表对象传递给Update_OI,并尝试而不是来使用选择/激活 - 您几乎总能避免这种情况,这样做会使您的代码更加健壮。< / p>

Sub UpdateAll()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        Update_OI ws
    Next ws
End Sub



Sub Update_OI(ws as Worksheet)
    Dim rng As Range, Colx As Long

    For Colx = 3 To 81

        Set rng = ws.Cells(10, Colx)

        If rng.Offset(-8, 0).Value <> "X" And _
           rng.Offset(-3, 0).Value <> 0 And _
           Len(rng.Value) > 0 Then 


            goalvalue = ws.Cells(70, Colx).Value

            ws.Cells(69, Colx).GoalSeek Goal:=goalvalue, _
                   ChangingCell:=ws.Cells(10, Colx)
        End If

    Next Colx

End Sub

答案 1 :(得分:0)

代码下方

Public Sub main()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        ws.Cells(1, 2).Value = 11111
    Next ws
End Sub

尝试更改

Dim ws As Worksheet For Each ws In ActiveWorkbook.Worksheets    
     Call Update_OI    
Next ws

Dim ws As Worksheet 
For Each ws In ActiveWorkbook.Worksheets    
     Call Update_OI    
Next ws

或者只是复制粘贴格式化问题。在这种情况下,我将删除我的答案,因为它没有答案:)。

答案 2 :(得分:0)

更改您的更新,如下所示。它现在应该工作。

Sub UpdateAll()
   Dim ws As Worksheet
   For Each ws In ActiveWorkbook.Worksheets
        ws.Select
        Call Update_OI
    Next ws

  End Sub