有条件的if()不能在嵌套循环中工作

我在两个工作簿中循环工作表。 如果两本书都有相匹配的工作表,那么我就把一本书的范围从一本书转移到另一本。 (这在下面注释)

我也跟踪哪本工作表出现在一本书中,而不是另一本(导致没有转移),这是我遇到问题的地方。 我只对包含“ – ”的表单感兴趣,并将我的集合放置在条件中,但不包含“ – ”的表单仍在添加。

我认为问题在于外部循环? 它不会在内部添加,但是当外部再次出现时,会触发.add ? 所以也许更好的问题是,循环testing匹配工作表的逻辑是什么?

 For Each ws In lastWB.Worksheets Set lastWS = ws lastName = lastWS.Name For Each s In ThisWorkbook.Worksheets If InStr(1, s.Name, "-") Then If s.Name = lastName And s.Range("C3").Value <> "5860" Then Debug.Print lastName 's.Range("C14:O48").Value = lastWS.Range("C14:O48").Value Else skippedAct.Add lastName 'still adding sheets that do not contain "-" End If End If Next Next 

你的嵌套循环可能会令人困惑,我认为这是你的问题的来源,正如在OP的评论中所解释的那样:当Instr返回False ,你将lastName添加到集合中,但是因为你正在检查lastWB中的每个工作表在ThisWorkbook表中,你会得到意想不到的结果。

这将是一个使用自定义函数的好地方:

 Function SheetExists(sName as String, wb as Workbook) 'Function which will check the presence of a sheet in a given workbook Dim ret On Error Resume Next Set ret = wb.Worksheets(sName) SheetExists = (Err.Number = 0) End Function 

摆脱嵌套循环,只要For each s in ThisWOrkbook.Worksheets ,像这样:

  For Each s In ThisWorkbook.Worksheets If InStr(1, s.Name, "-") Then If SheetExists(s.Name, lastWB) And s.Range("C3").Value <> "5860" Then s.Range("C14:O48").Value = lastWB.Worksheets(s.Name).Range("C14:O48").Value Else skippedAct.Add s.Name 'still adding sheets that do not contain "-" End If End If Next 

请注意Instr函数不会返回Boolean (True / False)。 相反,它返回一个Integer ,其中包含find的值的位置。 所以,尝试使用像这样的东西:

If InStr(1, s.Name, "-") > 0 Then

 For Each ws In lastWB.Worksheets Set lastWS = ws lastName = lastWS.Name 'if lastWG has "-", skip it. If InStr(1, lastName, "-") Then For Each s In ThisWorkbook.Worksheets 'If the names match, move forward (any with a "-" will have already been skipped) If s.Name = lastName And s.Range("C3").Value <> "5860" Then Debug.Print lastName 's.Range("C14:O48").Value = lastWS.Range("C14:O48").Value Else 'If lastName does not have "-" and does not match the current sheet, log it skippedAct.Add lastName End If Next End If Next 

这将logging此工作簿中不匹配的每个工作表的lastName。 我会猜测你只想logging它,如果它没有被发现…所以我会这样做:

 Dim logLast as Boolean For Each ws In lastWB.Worksheets Set lastWS = ws lastName = lastWS.Name 'if lastName has "-", skip it. If InStr(1, lastName, "-") Then LogLast = True For Each s In ThisWorkbook.Worksheets 'If the names match, move forward (any with a "-" will have already been skipped) If s.Name = lastName And s.Range("C3").Value <> "5860" Then logLast = False Debug.Print lastName 's.Range("C14:O48").Value = lastWS.Range("C14:O48").Value End If Next If logLast then skippedAct.Add lastName End If Next