停止循环以在少数工作表上工作

时间:2014-04-25 09:25:01

标签: vba excel-vba excel

Sub Macro5()
    Dim filename As String
    Dim MyRefAddr As String
    Dim MyCopyAddr As String
    Dim MyDestAddr As String
    Dim NoOfCols As Integer
    Dim lastRow As Long
    Dim Distributor As String
    Dim Z As Double
    Dim Davg As Double
    Dim LT As Long
    Dim temp As Long

    Worksheets.Add(Before:=Worksheets(1)).Name = "Norms"
    Sheets("Norms").Select
    Range("A1").Select
    ActiveCell.Value = "SKU"
    MyCopyAddr = Range("A1").Offset(1, 0).Address
    Range("A1").Offset(1, 0).Select
    ActiveCell.FormulaR1C1 = "=Sheet3!RC"
    Range(MyCopyAddr).AutoFill Destination:=Range(MyCopyAddr + ":A69")

    For Each ws In ActiveWorkbook.Sheets
        If ws.Name <> "Sheet1" And ws.Name <> "Norms" And ws.Name <> "Sheet3" And ws.Name <> "Sheet4" Then
            Range("B5").Select
            Selection.End(xlToRight).Select
            MyRefAddr = ActiveCell.Address
            NoOfCols = Application.WorksheetFunction.Count(Range("B5:" + MyRefAddr))
            'STDEV
            MyCopyAddr = Range(MyRefAddr).Offset(-1, 1).Address
            Range(MyRefAddr).Offset(-1, 1).Select
            ActiveCell.Value = "Sigma D"
        End If
    Next ws
End Sub

代码中的错误是什么。代码将进入&#34;规范&#34;表格和计算,尽管排除它

2 个答案:

答案 0 :(得分:0)

代码在Norm表中计算,因为它是活动工作表。循环中的所有范围都指的是活动表。您应该避免使用select和activate:

How to avoid using Select in Excel VBA macros

编辑:进行一些清理并删除所有“选择”和“激活”

Sub Macro5()
    Dim ws As Worksheet
    Dim NoOfCols As Integer
    Dim workSheetNorm As Worksheet, cell As Range

    Set workSheetNorm = Worksheets.Add(Before:=Worksheets(1))
    'workSheetNorm.Name = "Norms"


    Set cell = workSheetNorm.Range("A1")
    cell.Value = "SKU"

    Set cell = cell.Offset(1, 0)
    cell.FormulaR1C1 = "=Sheet3!RC"
    cell.Offset(1, 0).AutoFill Destination:=workSheetNorm.Range(cell.Offset(1, 0), "A69")

    For Each ws In ActiveWorkbook.Sheets
        If ws.Name <> "Sheet1" And ws.Name <> "Norms" And ws.Name <> "Sheet3" And ws.Name <> "Sheet4" Then
            Set cell = ws.Range("B5", ws.Cells(5, ws.Columns.Count).End(xlToLeft))

            NoOfCols = Application.WorksheetFunction.Count(cell)
            'STDEV
            cell.Offset(-1, 1).Value = "Sigma D"
        End If
    Next ws
End Sub

答案 1 :(得分:0)

您只需要将所有范围引用到ws
像这样的东西?:

For Each ws In ActiveWorkbook.Sheets 
    If ws.Name <> "Sheet1" And ws.Name <> "Norms" And ws.Name <> "Sheet3" And ws.Name <> "Sheet4" Then
        ws.Range("B5").Select 
        Selection.End(xlToRight).Select 
        MyRefAddr = ActiveCell.Address 
        NoOfCols = Application.WorksheetFunction.Count(ws.Range("B5:" + MyRefAddr)) 'STDEV 
        MyCopyAddr = ws.Range(MyRefAddr).Offset(-1, 1).Address 
        ws.Range(MyRefAddr).Offset(-1, 1).Select 
        ActiveCell.Value = "Sigma D" 
    End If 
Next ws