如何在不知道工作表的确切数量的情况下从所有工作表中选择特定单元格?

时间:2016-02-02 12:26:31

标签: excel vba numbers worksheet

我是一个初学者。这是我的代码的一部分:

Workbooks("xxx").Worksheets(1).Activate
Range("A1").Select
Selection.Copy

Workbooks("yyy").Worksheets(1).Activate
Range("B2").Select
ActiveSheet.Paste

Workbooks("xxx").Worksheets(2).Activate
Range("A2").Select
Selection.Copy

Workbooks("yyy").Worksheets(1).Activate
Range("B3").Select
ActiveSheet.Paste

每个xxx工作簿包含未知数量的工作表。它可以是3,它可以是50.如果我手动复制&粘贴上面的代码,例如。 50次,如果工作表的数量等于30,宏将显示错误并停止。我该如何自动化?请记住,我是新手,所以请简单回答。

2 个答案:

答案 0 :(得分:0)

尝试以下代码。

Dim wbX As Workbook
Dim wbY As Workbook
Set wbX = Application.Workbooks("xxx")
Set wbY = Application.Workbooks("yyy")

For i = 1 To wbX.Sheets.Count
  wbX.Sheets(i).Activate
  Range("A" & i).Select
  Selection.Copy

  wbY.Sheets(1).Activate
  Range("B" & i + 1).Select
  ActiveSheet.Paste
Next

答案 1 :(得分:0)

Siva回答。谢谢!

Dim wbX As Workbook
Dim wbY As Workbook
Set wbX = Application.Workbooks("xxx")
Set wbY = Application.Workbooks("yyy")

For i = 1 To wbX.Sheets.Count
wbX.Sheets(i).Activate
Range("A1").Select
Selection.Copy

wbY.Sheets(1).Activate
Range("B" & i + 1).Select
ActiveSheet.Paste
Next