以编程方式创建具有名称冲突的表单 [英] Programmatically created form with name conflict
问题描述
我正在Excel VBA中使用代码创建表单.以下代码段提出了一个问题,即以某种方式创建了已经正确设置名称的表单,然后,在我设置上述变量的唯一地方,它提出了一个问题,即存在一个使用该名称的表单(以防万一).
I'm creating in Excel VBA a form using code. The following code snippet presents a problem in which the form is somehow created with the name already correctly set and then afterwards, in the only place where I set the said variable, it raises an issue saying that there is a form with that name (the variable in case).
这是我的代码:
Dim frmName As String
frmName = "frm_" & Replace(CStr(Nome_do_formulario), " ", "")
Set myForm = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm)
With myForm
.Properties("Caption") = Nome_do_formulario
.Properties("Width") = 300
.Properties("Height") = 270
.Properties("Name") = frmName
End With
要清楚,错误是它到达该行时:
To be clear, the error is that when it reaches the line:
Set myForm = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm)
它已经以某种方式创建了一个在with
语句之后设置的名称的表单:
Somehow it already creates a form with name that's set after at the with
statement:
With myForm
.Properties("Caption") = Nome_do_formulario
.Properties("Width") = 300
.Properties("Height") = 270
.Properties("Name") = frmName '<- HERE
End With
然后,当它尝试运行with
语句时,它中断并说该名称的表单已经存在.
And then, when it tries to run the with
statement it breaks and says that a form with that name already exists.
整个事情在另一个模块中运行为:
The whole thing is ran at another module as:
Public Sub Main()
Dim ac As autoCrud
Set ac = New autoCrud
ac.CreateCRUDView
End Sub
表单创建在ac.CreateCRUDView
内部进行.
它如何在设置名称变量之前将其拉出,然后尝试使用它来创建另一个具有相同名称的表单?
How is it pulling the name variable before it's set and then trying to use it to make another form with the same name?
推荐答案
关于VBA项目中的UserForms集合,VBE遭受严重破坏. 即使您从项目中明确删除UserForm,也可能会以编程方式(有时以通常的方式)以相同的名称创建另一个用户窗体时会出错.
VBE suffers heavily corruption when it is about UserForms collection in a VBA Project. Even if you remove explicitly a UserForm from your project, you might get errors creating programatically (and sometimes in the normal way) another with the same name.
尝试使用这种方法:
Dim frmName As String
Dim myForm As VBComponent
frmName = "frm_" & Replace(CStr(Nome_do_formulario), " ", "")
ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm).Name = frmName
Set myForm = ThisWorkbook.VBProject.VBComponents(frmName)
With myForm
.Properties("Caption") = Nome_do_formulario
.Properties("Width") = 300
.Properties("Height") = 270
End With
请记住,如果删除新创建的用户窗体并以相同的Nome_do_formulário
值运行此代码,则会收到错误消息.
Remember, if you delete the newly created userform and run this code with the same Nome_do_formulário
value, you'll get an error.
这篇关于以编程方式创建具有名称冲突的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!