简体   繁体   English

Excel VBA以编程方式添加代码用户窗体

[英]Excel VBA add code userform programmatically

I got a tricky issue with my VBA-code. 我的VBA代码有一个棘手的问题。 The situation is that I have a manual created userform. 情况是,我有一个手动创建的用户表单。 I add controls to the userform with a macro and it works fine for me. 我使用宏将控件添加到用户窗体,对我来说效果很好。 But now I also need to add event-code to the userform. 但是现在我还需要将事件代码添加到用户表单中。 Following code I want to add with .CodeModule.InsertLines . 以下代码我想添加.CodeModule.InsertLines The important part is that the textboxes, which I want to call should work variably, but it doesn't work, any ideas how to fix this? 重要的是,我要调用的文本框应该可变地工作,但不起作用,有什么想法可以解决此问题? (Textboxes are named like this: textbox_0, textbox_1 and following) (文本框的命名如下:textbox_0,textbox_1及以下)

Dim iMaxColumns As Integer
Dim iCount As Integer 

iMaxColumns = Tabelle4.Cells(8, 2).Value
Dim vArray(0 To iMaxColumns - 1) As String


For iCount = 0 To iMaxColumns - 1
    vArray(iCount) = textbox_ & iCount &.Value
Next

'do sth. with the arrray

I assume the problem is that I can't add variables to my textbox object. 我认为问题是我无法向文本框对象添加变量。 I also could work with the complete path to my textbox calling it with .Designer.Controls("textbox_" & iCount & "") but that is a bunch of code and I hope to avoid that. 我还可以使用.Designer.Controls("textbox_" & iCount & "")调用文本框的完整路径,但这是一堆代码,我希望避免这种情况。

I figured out a quite easy way to solve my problem. 我想出了一种解决问题的简便方法。 I wrote all the necessary code in a seperate module. 我在单独的模块中编写了所有必要的代码。 There I can address all the variables and information I need. 在这里,我可以解决我需要的所有变量和信息。 After that when creating the UserForm I just copy all the code into the UserForms code block. 之后,在创建UserForm时,我只需将所有代码复制到UserForms代码块中。

Public Function edit_userform(strUserForm As String, _
strUserFormEvents As String)
    Dim VBProj As VBIDE.VBProject
    Dim VBComp As VBIDE.VBComponent
    Dim VBComp_Event As VBIDE.VBComponent
    Dim strCode As String

    Set VBProj = ActiveWorkbook.VBProject
    Set VBComp = VBProj.VBComponents(strUserForm)
    Set VBComp_Event = VBProj.VBComponents(strUserFormEvents)

    With VBComp_Event.CodeModule
        strCode = .Lines(1, .CountOfLines)
    End With

    VBComp.CodeModule.AddFromString strCode
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM