【问题标题】:VBA to run macro then loop through other sheetsVBA 运行宏然后遍历其他工作表
【发布时间】:2020-02-13 09:34:11
【问题描述】:

我正在尝试(但失败)让一些代码在每个工作表上运行,除了一个特定的工作表。我希望代码只剪切单元格 n2:s2 中的数据并将其粘贴到 t1:y1 中,然后对在 n3:s3、n4:s4、n5:s5 列中具有数据的任何其他行重复此操作。

一旦没有数据(我相信第 6 行),它应该移动到下一张表(“报告”表除外)。 我调试时面临的问题是它按预期移动数据,然后在同一张纸上重新开始,因此用空单元格覆盖数据。

Sub MovethroughWB()

    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets 'This statement starts the loop

        If ws.Name <> "Report" Then 'Perform the Excel action you wish (turn cell yellow below)

            Range("N2:S2").Select
            Selection.Cut Destination:=Range("T1:Y1")
            Range("T1:Y1").Select
            Range("N3:S3").Select
            Selection.Cut Destination:=Range("Z1:AE1")

        End If

    Next ws

End Sub

我确定它是基本的,但找不到什么!

【问题讨论】:

  • if 之后使用With ws,在End if 之前使用End With 在其他情况下,Excel 会在活动表中执行所有操作
  • 哇 - 我认为它有效 - 现在只是测试它 - 感谢 Teamothy
  • 我说得太早了..不确定发生了什么,但它不再工作了:(我的代码是 Sub MovethroughWB2() Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets '这个语句开始loop If ws.Name "Report" Then '执行您希望的 Excel 操作(将下面的单元格变为黄色) With ws Range("N2:S2").Select Selection.Cut Destination:=Range("T1:Y1") Range("T1:Y1").Select Range("N3:S3").Select Selection.Cut Destination:=Range("Z1:AE1") End With End If Next ws End Sub

标签: excel vba loops


【解决方案1】:

试试:

Sub MovethroughWB()

    Dim ws As Worksheet
    Dim i  As Long, Lastrow As Long, Lastcolumn As Long

    For Each ws In ThisWorkbook.Worksheets 'This statement starts the loop
        If ws.Name <> "Report" Then 'Perform the Excel action you wish (turn cell yellow below)
            With ws
                Lastrow = .Cells(.Rows.Count, "N").End(xlUp).Row
                For i = 2 To Lastrow
                    If .Range("N" & i).Value <> "" And .Range("O" & i).Value <> "" And .Range("P" & i).Value <> "" _
                        And .Range("Q" & i).Value <> "" And .Range("R" & i).Value <> "" And .Range("S" & i).Value <> "" Then
                        If .Range("T1").Value = "" Then
                            .Range("N" & i & ":S" & i).Cut .Range("T1:Y1")
                        Else
                            Lastcolumn = .Cells(1, .Columns.Count).End(xlToLeft).Column + 1
                            .Range("N" & i & ":S" & i).Cut .Range(.Cells(1, Lastcolumn), .Cells(1, Lastcolumn + 5))
                        End If
                    End If
                Next i

                .Rows("2:" & Lastrow).EntireRow.Delete

            End With

        End If

    Next ws

End Sub

【讨论】:

  • 非常感谢您的代码 - 它有点工作....我需要它来将 n2:s2 中的数据移动到 t1:y1 并将数据从 n3:s3 移动到 z1:ae1,所以所有数据都位于第 1 行,然后我将删除第 2 行和第 3 行等
  • 如何在移到下一张之前删除除第 1 行之外的所有内容?
猜你喜欢
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
相关资源
最近更新 更多