在if语句中添加IsWorkBookOpen后,vba类型不匹配

时间:2016-09-08 23:42:18

标签: vba excel-vba excel

我有一些工作的代码:

WbShortage = "name.xlsm"
For l = TotalDefectsPerPieces + 1 To TheLastRow
            For i = StartDate To EndDate
                    Date = Cells(DateRow, i).Value
                    [...]
                    With Workbooks(WbShortage).Worksheets("Report")[...]

然后我添加了这个以检查打开了哪个文件(有两个选项):

WbShortage1 = "name.xlsm"
WbShortage2 = "name2.xlsm"
If IsWorkBookOpen(WbShortage1) = True Then
   WbShortage = WbShortage1
   Else
   WbShortage = WbShortage2
End If
For l = TotalDefectsPerPieces + 1 To TheLastRow
            For i = StartDate To EndDate
                    Date = Cells(DateRow, i).Value
                    [...]
                    With Workbooks(WbShortage).Worksheets("Report")[...]

现在行Date = Cells(DateRow, i).Value中存在类型不匹配错误。当我删除I​​f语句一切都很好。我只是没有得到它,这一行决不依赖于WbShortage,因为它对应于另一个Wb。

当然我有这个功能:

Function IsWorkBookOpen(sWB)
On Error GoTo NotOpen
Workbooks(sWB).Activate
IsWorkBookOpen = True
Exit Function
NotOpen:
IsWorkBookOpen = False
End Function

1 个答案:

答案 0 :(得分:2)

这一天出现在这里多次:在非工作表代码模块中,您需要确保使用工作表参考符合对CellsRange的所有来电的限制,否则他们将所有都在活动工作表的范围内执行(并且您的IsWorkBookOpen函数会更改...)

请参阅:What is the default scope of worksheets and cells and range?

您的功能可能更好地写为:

Function IsWorkBookOpen(sWB) As Boolean
    Dim wb As Workbook

    On Error Resume Next
    Set wb = Workbooks(sWB)
    On Error Goto 0

    IsWorkBookOpen = Not wb Is Nothing

End Function

...这可以避免更改“活动”工作簿的副作用,但真正的解决方案是使用工作表来限定Cells

@ Mat' sMug - 关于功能和副作用的是什么?