Reference UserForm.TextValue1 from VB code query

我是研究僧i 提交于 2020-04-30 16:31:13

问题


i have a pre-created xlsm workbook that has inside of it some userforms that i'd like to set with values from some VB code. So I can access, open and show the workbook everything is going fine there but I'm having an issue in getting the syntax/terminology correct for interactibg with userforms.

my code looks something like this:

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.

now ive spent a while looking for solutions and i can find multiple references to VBA to VBA calls and hundreds of articles on calling other elements of a VBA project from VB but i can't seem to find anything particular on referencing userforms from a VB project.

Im guessing on my work so far that userforms 'dont exist' at run time and i need to create an object of it to manipulate from the VB code but i can't find the syntax of how to reference userforms correctly.

anyone got any ideas?

EDIT: small clarification GEtWorkbook() is a predefined task sorry for not provising clarity on that basically it opens a target workbook at instance handle and workbook name includes filepath as well as name together to point to a workbook.


回答1:


There is no need to use wb.UserForm1.TextBox1. Instead use this:

UserForm1.TextBox1.Value = "abcd"

To make all controls on a UserForm Visible use this in the UserForm_Initialize Event:

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


来源:https://stackoverflow.com/questions/55728191/reference-userform-textvalue1-from-vb-code-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!