使用vba进行userform,commandbutton不起作用

时间:2015-05-29 12:13:09

标签: excel vba userform

首先,我来自荷兰,很抱歉我的英语不好。

我有一张包含大量记录的excelsheet(从10到1000,具体取决于用户)。我的想法是动态地创建一个userform,其中每个记录创建一行文本框。然后我想为每条记录创建一个命令按钮来更改记录中的数据。最后,我向userform添加了一些代码,以定义单击commandbutton时执行的操作。

当显示用户窗体时,文本框和命令按钮是可见的,但是当我单击命令按钮时没有任何反应,尽管代码是在用户窗体上创建的。

我有一个示例文件,但我不知道如何在此处上传它。

下面是代码(放在用户表单下)

Private Sub UserForm_Initialize()
Dim cCntrl As Control
Dim txtB1 As Control
Dim cmb1 As Control

'Deleting lines doesn't work yet
'With ThisWorkbook.VBProject.VBComponents("EFRIS").CodeModule
'x = .countoflines
'y = Sheets("Data").Range("A3").Value
'If x > y Then .DeleteLines y, x - y
'x = .countoflines
'End With
'
'Sheets("data").Range("A3") = x

'locatie van de userform in het midden van het scherm plaatsen
'breedte van de userform aanpassen aan de breedte van het scherm
'hoogte van de userform aanpassen aan de hoogte van het scherm
a = Application.Width
b = Application.Height
EFRIS.Left = 5
EFRIS.Width = a - 25
EFRIS.Height = b - 50

'e = de .left van de eerste tekstbox
e = 100

'f = het aantal records in de sheet ("FRIS")
f = Sheets("FRIS").Range("B10000").End(xlUp).Row - 2

'a is de loop in rijen
For a = 1 To f
'b = de loop in kolommen
For b = 1 To 8
If b = 1 Then c = "a"
If b = 2 Then c = "b"
If b = 3 Then c = "c"
If b = 4 Then c = "d"
If b = 5 Then c = "e"
If b = 6 Then c = "f"
If b = 7 Then c = "g"
If b = 8 Then c = "h"
'If b = 9 Then c = "i"
'If b = 10 Then c = "j"

'breedte per textbox
If b = 1 Then d = 30
If b = 2 Then d = 100
If b = 3 Then d = 100
If b = 4 Then d = 130
If b = 5 Then d = 150
If b = 6 Then d = 150
If b = 7 Then d = 150
If b = 8 Then d = 50
'If b = 9 Then d = 100
'If b = 10 Then d = 30

Set txtB1 = Controls.Add("Forms.TextBox.1", "TB" & a & b, True)
With txtB1
    .Height = 20
    .Width = d
    .Left = e
    .Top = 5 + (a * 20)
    .Value = Sheets("FRIS").Range("A2").Offset(a, b)
    .Locked = True
End With

'.left van de textbox
e = e + d

Next
'E resetten naar 100
e = 100

Set cmb1 = Controls.Add("Forms.CommandButton.1")
With cmb1
    .Caption = "Wijzigen"
    .Height = 20
    .Width = 90
    .Left = 5
    .Top = 5 + (a * 20)
End With

With ThisWorkbook.VBProject.VBComponents("EFRIS").CodeModule
x = .countoflines
Sheets("Data").Range("A3") = x
'.InsertLines x + 1, "Private Sub " & cmb1.Name & "_Click()"
'.InsertLines x + 2, "AStart.show"
'.InsertLines x + 3, "Unload Me"
'.InsertLines x + 4, "End Sub"
End With


'g bepaald de totale hoogte van de userform voor de scrollbar
g = 20 + a * 20
Next

EFRIS.ScrollBars = fmScrollBarsVertical
EFRIS.ScrollTop = 0
EFRIS.ScrollHeight = g

EFRIS.Show

End Sub

2 个答案:

答案 0 :(得分:1)

Assign code to a button created dynamically

以上可能对您有所帮助。您需要实际为按钮分配代码。在上面的链接中有两种方法可以做到这一点。

答案 1 :(得分:0)

单击Sub CommandButton1_Click()中的按钮时,必须添加要运行的代码,其中CommandButton1是按钮名称。

要创建此Sub,请双击表单设计器中的按钮。

在加载表单时执行Sub UserForm_Initialize()。