通过工作簿中的每个工作表循环VBA宏

时间:2016-07-21 16:40:31

标签: vba loops

我遇到一些工作表循环问题。

我正在尝试开发一个可以替换每个工作表中所有分区错误的宏。宏的替换部分工作,就好像我只是将它应用于第一个工作表。但是,一旦我添加了工作簿循环,它就会指出这一行" CurrentWS.Cells(i,j).Formula = NewFormula"不再正确了。我的想法是因为循环工作表和活动表被抛弃了?

任何建议将不胜感激!谢谢!

Sub ReplacingFormula2()

Dim CurrentWS As Worksheet
Dim AllWs As Worksheet
Dim Temp As String
Dim Temp2 As String
Dim Divider As String
Dim NewFormula As String
Dim ColNum As Long
Dim i As Integer
Dim j As Integer
Dim SlashPosition As Integer


Application.ScreenUpdating = False
Application.EnableEvents = False

Set CurrentWS = ActiveSheet

For Each AllWs In ActiveWorkbook.Worksheets

' the For i loop works appropriate if just for 1 worksheet
RowNum = CurrentWS.Cells(Rows.Count, "B").End(xlUp).Row

    For i = 1 To RowNum
        ColNum = CurrentWS.Cells(i, Columns.Count).End(xlToLeft).column
            For j = 3 To ColNum
                Temp = CurrentWS.Cells(i, j).Formula
                SlashPosition = InStr(Temp, "/")
                If (SlashPosition > 0) Then
                    Divider = Mid(Temp, SlashPosition + 1)
                    Temp2 = Mid(Temp, 2)
                    NewFormula = "=IF(" & Divider & "=0,0," & Temp2 & ")"
                    ' this is the line that gives error after adding loop through the workbook
                    CurrentWS.Cells(i, j).Formula = NewFormula
                End If
            Next j
    Next i

Next

CurrentWS.Activate
Application.EnableEvents = True

End Sub

0 个答案:

没有答案