Excel VBA:工作簿_打开

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13946645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 18:53:41  来源:igfitidea点击:

Excel VBA: Workbook_Open

excelvbaworksheet

提问by dud

I'm using Workbook_Open to call a userform when the application is opened, this is working fine. However I would like it to only run the first time it is opened. I tried this and it work if I run the sub from the editor but not when I open the file.

我正在使用 Workbook_Open 在打开应用程序时调用用户表单,这工作正常。但是我希望它只在第一次打开时运行。我试过这个,如果我从编辑器运行 sub ,它会工作,但当我打开文件时不会。

Sub Workbook_Open()
If Worksheets("DataSheet").Range("A1").Value = "" Then
     QuickStartForum.Show
End If
End Sub

Note: A1 contains a value that will be populated after the user form has run

注意:A1 包含一个将在用户表单运行后填充的值

It appears that the problem is that it opens the user form before the data is loaded into the worksheet.

问题似乎在于它在将数据加载到工作表之前打开了用户表单。

Is this there a way around this or do I need to take a different approach ?

有没有办法解决这个问题,还是我需要采取不同的方法?

回答by Chris

I think it is because you have this code in a Module. You need to put the code within 'ThisWorkBook'.

我认为这是因为您在Module. 您需要将代码放在“ ThisWorkBook”中。

I tried this following code and had no issues when it was in the 'ThisWorkBook' it failed to run within 'Module1'

我尝试了以下代码,当它在 ' ThisWorkBook' 中时没有问题,它无法在 ' Module1'内运行

Private Sub Workbook_Open()
    If Worksheets("DataSheet").Range("A1").Value = "" Then
         QuickStartForum.Show
         Worksheets("DataSheet").Range("A1").Value = "filled" ' <-- this fills the cell with data for testing, so that when you reopen the file it should not re-open the userform
    Else
        MsgBox ("not shown because the A1 cell has data")
    End If
End Sub