Excel for Each ws不会转到下一个ws

时间:2018-09-19 16:16:33

标签: excel vba excel-vba loops

背景-我正在使用一本工作簿,其中包含大量工作表和许多数据,这些数据受到公式的破坏。我想用此代码完成一些步骤:

  • 取消隐藏所有隐藏的行/列
  • 仅使用值/格式粘贴所有数据。

我能够在一个工作表上成功完成这些任务,但不会继续进行-它将尝试一遍又一遍地重复在同一工作表上重复执行相同的操作。

Sub Macro1
    Dim ws As Worksheet

    For Each ws In ActiveWorkbook.Worksheets
        'Have also tried "For Each ws In ThisWorkbook.Worksheets at other users suggestions.
        ws.Cells.Activate
        ws.Cells.EntireColumn.Hidden = False
        ws.Cells.EntireRow.Hidden = False
        If ActiveSheet.FilterMode Then
            ActiveSheet.ShowAllData
        End If
        ws.Cells.Activate
        ws.Cells.Copy
        ws.Cells.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

        'I put these in here thinking that it might be related to the copying/pasting
        'action that was prohibiting it from changing sheets.

        Application.CutCopyMode = False
        ws.Cells(1, 1).Select  
    Next ws

End Sub

非常感谢任何帮助!!!为了解决这个问题,我(从字面上)将头发从头上拉了近一个星期……我越来越绝望了!谢谢!

1 个答案:

答案 0 :(得分:2)

尝试以下操作:

Sub Macro1
    Dim ws As Worksheet

    For Each ws In ActiveWorkbook.Worksheets
        ws.Cells.EntireColumn.Hidden = False
        ws.Cells.EntireRow.Hidden = False
        If ws.FilterMode Then ws.ShowAllData
        ws.UsedRange.Value = ws.UsedRange.Value
    Next ws
End Sub