Windows(变量)。激活错误

时间:2016-01-27 12:37:42

标签: excel vba

Dim filepath As String
filepath = ActiveWorkbook.Path + "\"
Application.ScreenUpdating = False
Dim file As String
Dim fullfilepath As String
file = Dir$(filepath & "*Example*" & ".*")
fullfilepath = filepath & file
Application.EnableEvents = False
Workbooks.Open (fullfilepath)
Windows(file).Activate
Application.EnableEvents = True

使用上面的代码,非常愉快地填充文件路径,非常高兴地找到文件'New Example.xlsm',并且fullfilepath也正确。

当它到达Windows(文件).Activate我得到一个超出范围的下标错误(在它进一步得到之前)

这是明显的吗?它适用于我的另一个编码示例。

1 个答案:

答案 0 :(得分:1)

Dim filepath As String
filepath = ActiveWorkbook.Path + "\"

Application.ScreenUpdating = False

Dim file As String
Dim fullfilepath As String

file = Dir$(filepath & "*Example*" & ".*")
fullfilepath = filepath & file

Application.EnableEvents = False

Dim NewWB As Workbook
Set NewWB = Workbooks.Open (fullfilepath)

Set ActiveWindow = NewWB

Application.EnableEvents = True

我相信这更优雅,更容易使用。如果将NewWB声明为静态变量或公共变量,则可以将其用作多个模块或子变量的引用。 :)