反复打开用户表单中的用户表单会导致对象问题

我目前已经在Excel 2003中build立了一个工具,它显示了一系列的数据input表单。 客户要求在表单上有“上一个表格”和“下一个表格”button。

用于在表单之间移动的代码如下所示

Sub NextForm(strFormName As String) Dim intCurPos As Integer Dim strNewForm As String 'Find out which form we are currently on from a list in a range intCurPos = WorksheetFunction.Match(strFormName, Range("SYS.formlist"), 0) If intCurPos = WorksheetFunction.CountA(Range("SYS.formlist")) Then 'We want to use the first one intCurPos = 0 End If 'Get the name of the form to open strNewForm = WorksheetFunction.Index(Range("SYS.formlist"), intCurPos + 1) 'Load the form into the Userforms Collection Set newForm = VBA.UserForms.Add(strNewForm) 'Show the form newForm.Show End Sub 

我遇到的问题是,你做了这25次(是的,我知道)系统崩溃。 我意识到这是因为每当你到达上面的newForm.Show行代码不会完成,因此坐在内存中。

无模式的forms会阻止这个问题,但用户可以加载其他forms,并做其他事情会导致重大问题。

有没有人有任何build议来帮助这个? 以某种方式强制执行代码,但不阻止窗体的模态能力?

远射,但感谢任何帮助。

也许你应该改变你的方法。

我会build议如下:

在主模块中,每次用户按下“下一个表格”button时,使用一个循环来循环打开表格和循环。

 'This sub in your main Module sub ShowAndCyleForms Dim FormName As String Dim MyForm as Object Dim CloseForm as Boolean FormName = "frmMyForm" do while CloseForm=False set MyForm = VBA.UserForms.Add(FormName) MyForm.Show CloseForm=MyForm.CloseStatus FormName=MyForm.strNewForm Unload MyForm Set MyForm = Nothing loop end sub 

在每一种forms中,声明:

 Public CloseStatus as Boolean Public strNewForm as String 

在每个“下一个表格”button中,放置如下所示的内容:

 Private Sub btnNextForm_Click() CloseStatus=False strNewForm= NextForm(Me.Name) Me.Hide End Sub 

修改你的sub是一个函数,定义下一个表单名称

 Sub NextForm(strFormName As String) Dim intCurPos As Integer 'Find out which form we are currently on from a list in a range intCurPos = WorksheetFunction.Match(strFormName, Range("SYS.formlist"), 0) If intCurPos = WorksheetFunction.CountA(Range("SYS.formlist")) Then 'We want to use the first one intCurPos = 0 End If 'Get the name of the form to open NewForm = WorksheetFunction.Index(Range("SYS.formlist"), intCurPos + 1) ' End Sub 

您还需要修改“确定”以隐藏表单,而不是卸载它,并将CloseStatus设置为true。

这个想法是在一个单一的程序中控制你所有的表单从外部加载/卸载。

希望已经够清楚了。