首先我來自荷蘭,所以對於我的壞英語感到抱歉。用vba製作用戶表單,commandbutton不起作用
我有一個很多記錄(從10到1000,取決於用戶)的excelsheet。我的想法是動態地創建一個用戶表單,每個記錄創建一行文本框。然後我想爲每個記錄創建一個命令按鈕來更改記錄中的數據。最後我向用戶表單添加一些代碼來定義單擊commandbutton時執行的操作。
當顯示userform時,文本框和commandbutton是可見的,但是當單擊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
的[分配代碼來動態創建的按鈕上的Excel使用VBA](http://stackoverflow.com/questions/10224511/assign-code-to-a-button-created-dynamically-using-vba-可能重複on-excel) – USFBS