从VB代码查询中引用UserForm.TextValue1

时间:2019-04-17 13:02:59

标签: excel vba vb.net userform

我有一个预先创建的xlsm工作簿,里面有一些用户表单,我想用一些VB代码中的值进行设置。因此,我可以访问,打开和显示工作簿,那里一切都很好,但是在使语法/术语正确与用户表单进行交互时存在问题。

我的代码如下:

Dim wb as Object = getworkbook(handle, workbookname)
'i now have a workbook i can manipulate
'here i've left out a series of worksheet calls that happen and some other macro calls which I dont believe are relevant
'now i would like to reference the form that was named 'UserForm1' and in that form there are multiple text boxes with various titles so we'll just go with the first one 'TextBox1'.
' so i am trying to reference UserForm1.TextBox1 and set it to 'abcd'

'try 1 
wb.UserForm1.TextBox1 = "abcd"
'gives public member userform1 on type workbook not found

'try 2
wb.UserForm1.TextBox1.Value = "abcd"
'gives public member userform1 on type workbook not found

'try 3
'saw this on windows site but i dont get the syntax of calling them controls                     
'so im not confident in exactly how this was supposed to work
For Each Control in UserForm1.Controls
    Control.Visible = True
Next Control
'this was just to make it visible but it didnt work, i get compile errors of 
'UserForm1 not accessible maybe due to its protectionlevel.

现在我花了一段时间寻找解决方案,我可以找到从VB到VBA调用的多个VBA引用,以及数百篇关于从VB调用VBA项目的其他元素的文章,但是我似乎找不到任何有关从中引用用户窗体的东西一个VB项目。

到目前为止,我一直在猜测自己的工作,以至于用户窗体在运行时“不存在”,我需要创建一个对象来从VB代码进行操作,但是我找不到如何正确引用用户窗体的语法。 / p>

有人有什么主意吗?

编辑:简短的说明GEtWorkbook()是一个预定义的任务,由于没有提供清晰的信息,对不起,它基本上会在实例句柄处打开目标工作簿,并且工作簿名称包括文件路径以及一起指向工作簿的名称。

1 个答案:

答案 0 :(得分:0)

无需使用wb.UserForm1.TextBox1。而是使用此:

UserForm1.TextBox1.Value = "abcd"

要使用户窗体上的所有控件可见,请在UserForm_Initialize事件中使用此控件:

Sub UserForm_Initialize()
Dim ctrl as Control

For each ctrl in UserForm1.Controls
     If Typename(ctrl) = "TextBox" then
         ctrl.Visible = True
     End If
Next ctrl
End Sub