如何通过循环使用工作表名称将数据从一张工作表复制到不同工作簿中的另一工作表

时间:2018-08-19 05:03:06

标签: excel-vba

我想通过工作表名称将数据从“ Miz”工作表中的工作表复制到“ Prime”工作簿中的工作表。意思是,我希望通过循环将Miz工作表“资产”中的数据循环复制到工作簿“ Prime”中的工作表“资产”中(因为我有很多工作表),以此类推。

感谢您的帮助

p.s 我有代码可以工作,但它不会遍历所有工作表。它只复制第一个,仅此而已。

SELECT [Month]
     , SUM([Renters]) AS [Renters]
     , SUM([Returns]) AS [Returns]
  FROM (
         SELECT MONTH(createddate) AS [Month]
              , 1 AS [Renters]
              , 0 AS [Returns]
           FROM Bikes
             -- no WHERE because we want to count non-returned bikes
         UNION ALL
         SELECT MONTH(datereturned) AS [Month]
              , 0 AS [Renters]
              , 1 AS [Returns]
           FROM Bikes
          WHERE datereturned IS NOT NULL -- Only count returned bikes
       ) x
 GROUP BY [Month]
 ORDER BY [Month]

1 个答案:

答案 0 :(得分:1)

这可以做得更好,但是我很累。该代码循环遍历每个工作簿,并将源工作簿的使用范围复制到目标工作簿范围F1。两个工作簿都必须打开,否则您将收到Subscript out of range错误。

Sub WsLoop()
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim WsSource As Workbook
Dim WsTarget As Workbook
Dim Rng As Range

Set WsSource = Workbooks("Miz.xlsm")
Set WsTarget = Workbooks("Prime.xlsm")

    For Each ws In WsSource.Sheets
        Set Rng = ws.UsedRange

        For Each ws1 In WsTarget.Sheets
            If ws.Name = ws1.Name Then
                Rng.Copy Destination:=ws1.Range("F1")
            End If
        Next ws1
    Next ws

End Sub