对于工作表中的每个工作表不起作用

时间:2014-04-23 22:57:14

标签: excel vba loops excel-vba

我对VBA编码很新,所以请原谅我的无知,因为我可能在这里做了一件非常简单的错事。我已经编写了一个小的VBA脚本,它使用名称的主列表作为参考点来对齐工作表的数据。

它在一个工作表上一次正常工作,但是当输入到"对于工作表中的每个工作表"循环,它将它应用于第一个工作表,然后停止。我已经对它进行了调试,并为每个"进行了调试。部分工作正常,但代码并未通过第一个工作表。有什么提示吗?

我已尝试在"内部和外部移动Dim;对于每个"变量,它似乎没有任何区别。根据我的理解,代码中对工作表的所有引用都是随每一步而变化的变量。

我已根据建议对代码进行了编辑,但它似乎仍然只适用于第一个工作表:

Option Explicit

Sub AlignAll()
Dim Current As Worksheet
Dim n As Long, x As Long, i As Long, a As Range, c As Range
Set c = Worksheets("Masterlist").Range("A6:A200")

For i = 1 To ThisWorkbook.Worksheets.Count
    Set Current = ThisWorkbook.Sheets(i)
        If Current.Name <> "Yearly" And Current.Name <> "Masterlist" Then 'Prevent Conflicts
            n = Cells.SpecialCells(11).Row
            'sets a as the range of the current worksheet and c as range of the master list
            Set a = Current.Range("A6:A200")
            a(n + 1) = Chr(255): c(n + 1) = Chr(255)
            a.Sort a(1), 1, Header:=xlNo
            c.Sort c(1), 1, Header:=xlNo
            Do
            x = x + 1 'steps through each range
            If a(x) > c(x) Then 'adds rows as needed to align data
                a(x).EntireRow.Insert xlShiftDown
            End If
            If x > 10 ^ 4 Then Exit Do
            Loop Until a(x) = Chr(255) And c(x) = Chr(255)
            a(x).ClearContents: c(x).ClearContents 'resets variables
        End If
Next i
End Sub

2 个答案:

答案 0 :(得分:0)

以下是一些可能有用的补充调整,用'<~评论表示:

Option Explicit
Sub AlignAll()

Dim Current As Worksheet
Dim n As Long, x As Long
Dim a As Range, c As Range

'set static references up front
Set c = Worksheets("Masterlist").Range("A6:A200")

For Each Current In ThisWorkbook.Worksheets
    If Current.Name <> "Yearly" And Current.Name <> "Masterlist" Then '<~ skip master and yearly
        n = Current.Cells.SpecialCells(11).Row '<~ include sheet context
        'sets a as the range of the current worksheet
        Set a = Current.Range("A6:A200")
        a(n + 1) = Chr(255): c(n + 1) = Chr(255)
        a.Sort a(1), 1, Header:=xlNo
        c.Sort c(1), 1, Header:=xlNo
        Do
        x = x + 1 'steps through each range
        If a(x) > c(x) Then 'adds rows as needed to align data
            a(x).EntireRow.Insert xlShiftDown
        End If
        If x > 10000 Then Exit Do
        Loop Until a(x) = Chr(255) And c(x) = Chr(255)
        If x > 10000 Then MsgBox ("Do Loop possibly had an error, reached 10000!") '<~ warning for 10k loop
        a(x).ClearContents: c(x).ClearContents 'resets variables
    End If
Next Current

End Sub

答案 1 :(得分:0)

其他简单的解决方法:

Option Explicit

Sub AlignAll()
Dim Current As Worksheet
Dim Current As Worksheet
Dim n As Long, x As Long, i as Long '
Dim a As Range

on error resume next 'really needed ? might solve problems to (temporarely) remove it , to debug...

For i=1 to ActiveWorkbook.Worksheets.count
   set Current = ActiveWorkbook.Sheets(i)
   'Do Stuff
Next i
End Sub