我在两个工作簿中循环工作表。如果两本书中都有匹配的工作表,我会将一个范围从一本书转移到另一本书。 (这在下面说明。)
我也在跟踪哪本工作表出现在一本书而不是另一本书(导致没有转移),这是我遇到问题的地方。我只对包含" - "并将我的集合放在条件但不包含" - "仍在增加。
我认为问题在于外循环?它在内部没有添加但是当外部再次出现时,它会触发.add
?因此,或许更好的问题是,循环测试匹配工作表的逻辑是什么?
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
答案 0 :(得分:1)
请注意Instr
函数不返回Boolean
(True / False)。相反,它返回Integer
,其中包含找到的值的位置。所以,尝试使用类似的东西:
If InStr(1, s.Name, "-") > 0 Then
答案 1 :(得分:1)
您的嵌套循环可能会令人困惑,我认为这是您的问题的根源,如OP上的评论中所述:只要lastName
返回{Instr
,就会在集合中添加False
{ {1}},但由于您正在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
,如下所示:
<taglib>
<taglib-uri>http://java.sun.com/portlet</taglib-uri>
<taglib-location>/WEB-INF/tld/liferay-portlet.tld</taglib-location>
</taglib>
答案 2 :(得分:1)
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
这将记录此workbook中不匹配的每个工作表的lastName。如果根本找不到,我猜你只想记录它...所以我会这样做:
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