1

我正在尝试创建一个在打开工作簿时运行的代码。我尝试使用 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 文件尚未打开,因此在获取文件名时会出错。如何在打开代码但打开后执行代码?

4

1 回答 1

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.
于 2013-07-10T17:46:19.303 回答