在工作簿打开后运行auto_open

时间:2013-07-10 17:18:28

标签: excel excel-vba vba

我正在尝试创建在打开工作簿时运行的代码。我尝试使用Auto_open和workbook_open(在ThisWorkbook对象中)但是我对它们都有问题。问题是代码需要我正在打开的工作簿中的信息正如您在此代码中所看到的那样:

Sub Auto_Open()
Dim fileNam As String
Dim text As String
Dim answer As String
Dim question As String
Dim quesPos As Integer
MsgBox "add-in start"
'On Error GoTo GetOut


fileNam = ThisWorkbook.FullName
jsonFile = Replace(jsonFile, "xls", "survey.descriptor.json")
Open jsonFile For Input As #2
pos = 1
ThisWorkbook.Sheets("Result").Select
'The code gives the error here

由于excel文件尚未打开,因此在获取文件名时会出错。如何在打开代码时打开代码来执行代码?

1 个答案:

答案 0 :(得分:2)

如果你需要一些代码在工作簿打开后运行(而不是“正在打开”),一个解决方案就是创建一个定时事件 - 将计时器设置为5秒,在auto_open中触发它,并让它循环,直到文件“正确打开”。这可能看起来像这样:

Auto_Open()

fullyOpenTime = Now + TimeValue("00:00:05")
Application.OnTime alertTime, "LetsGo"

然后创建另一个将在工作簿打开后运行的子项:

Sub LetsGo()

On Error Resume Next

' loop around until no error was triggered
Do
  DoEvents
  fileName = Application.ActiveWorkbook.FullName
  Application.Wait DateAdd("s", 1, Now)  ' "cheap trick" to wait one second
While Err.Number <> 0

On Error GoTo 0
' when you get here, you have an active workbook.