从几个工作表中提取数据并将其放入摘要工作表(循环错误)

我已经创build了下面的代码,以便从工作簿中的多个工作表中获取特定的数据,并将它们放在汇总表中的行中。 它或者填充任何东西或者一遍又一遍地填充每一行。 它需要自动发生。

Sub Summary() Dim WkSht as Worksheet Dim Row as Integer 'A15 - A29: Pull over (A1) if > 0 'B15 - B29: Pull over (C1) if > 0 'C15 - C29: Pull over (D7) if > 0 For Each WkSht In ThisWorkbook.Sheets For Row = 15 To 29 If WkSht.Name Like "Tr. [0-9]*" Then If WkSht.Range("D7").Value > 0 Then If IsEmpty(Row) Then Cells(Row, 1).Value = WkSht.Range("A1").Value Cells(Row, 2).Value = WkSht.Range("C1").Value Cells(Row, 3).Value = WkSht.Range("D7").Value End If End If End If Next Row Next WkSht End Sub 

我怀疑以下更改将有所帮助(有点难以看到您的整个工作簿):

  1. 将摘要表定义为一个单独的实体 – 不要从中抓取数据
  2. 而不是testingisempty(Row) ,testing你想要的东西是空的(一个单元格吗? Row是一个variables,你设置了几行)
  3. 汇总表中的“参考Cells ”,而不是“自行”。 当你这样做的时候,你不能确定Excel会在想什么。
  4. 由于For Each循环中的For Row =循环,您一遍又一遍地复制相同的东西。 你只想为find的每个工作表增加一次Row

你最终得到的是 – 这是否工作?

 Sub Summary() Dim WkSht as Worksheet Dim summarySheet as Worksheet Dim Row as Integer 'A15 - A29: Pull over (A1) if > 0 'B15 - B29: Pull over (C1) if > 0 'C15 - C29: Pull over (D7) if > 0 Set summarySheet = ThisWorkbook.Sheets("Summary") ' whatever the right name is… Row = 15 For Each WkSht In ThisWorkbook.Sheets if Not (WkSht.Name = summarySheet.Name) Then If WkSht.Name Like "Tr. [0-9]*" Then If WkSht.Range("D7").Value > 0 Then If IsEmpty(summarySheet.Cells(Row,1)) Then summarySheet.Cells(Row, 1).Value = WkSht.Range("A1").Value summarySheet.Cells(Row, 2).Value = WkSht.Range("C1").Value summarySheet.Cells(Row, 3).Value = WkSht.Range("D7").Value End If End If End If Row = Row + 1 End If Next WkSht End Sub 

您在代码中的评论build议您要移动的东西,只有大于零,但您的代码只testing一个值; 你打算testing所有三个?