我希望使用一段代码来创建一系列按钮。每个按钮然后调用一个不同的子程序,称为“ loadboat”。我需要将变量传递给“ loadboat”,告诉它该怎么做。
“ loadboat”子例程已经编写,用于创建按钮的代码也已编写(请参见下文)。我知道如何将按钮的onclick代码设置为子例程,但不知道如何将变量传递给该子例程。下面显示的子例程创建一系列验证列表,每个列表下方都有按钮。每个按钮都需要调用一个子例程,并传递模型名称(在按钮正上方显示)和版本号(从按钮正上方的验证列表中选择)。
需要在创建按钮后进行验证选择,这意味着在创建按钮时未定义传递给“ loadboat”的参数。
j = 1
For i = 5 To B.UsedRange.Columns.Count 'iterate through all the models'
If B.Cells(2, i).Value <> 0 Then 'case where there are versions of that model in build'
A.Cells(5, 2 * j).Value = B.Cells(1, i).Value 'print name of the model'
k = B.Cells(2, i).Value - B.Cells(3, i).Value + 1 'set k = to the total number of that model ever to be in build - the number of that model completed before the start of this year'
ReDim Ar1(k) As String 'set Ar1 to be a size such that it can contain all the models versions I wish to display'
For l = 0 To k - 1 'iterate through all of the model versions and add them to an array'
If B.Cells(3, i).Value + l < 10 Then 'version number is less than 10'
Ar1(l) = ("00" & CStr(B.Cells(3, i).Value + l))
ElseIf l > 9 And l < 100 Then 'version number is between 10 and 100
Ar1(l) = ("0" & CStr(B.Cells(3, i).Value + l))
Else 'version number is greater than 100'
Ar1(l) = CStr(B.Cells(3, i).Value + l)
End If
m = m + 1
Next l
With A.Cells(7, 2 * j).Validation 'selecting the cell to place the listbox in and creating it'
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=Join(Ar1, ",") 'adding the array containing the the version numbers'
.InCellDropdown = True
.InputTitle = A.Cells(7, 2 * j).Value
End With
Set Ran1 = A.Range(A.Cells(9, 2 * j), A.Cells(9, 2 * j)) 'picking the cell to create the button in'
Set Btn = A.Buttons.Add(Ran1.Left, Ran1.Top, Ran1.Width, Ran1.Height) 'creating the button'
With Btn
.OnAction = "loadboat"
.Caption = "Edit"
.Name = "Btn" & j
End With
j = j + 1
End If
Next i
我不知道如何传递按钮运行变量的子程序
答案 0 :(得分:2)
以下代码创建按钮并分配参数以调用要调用的过程。您可以集成文字参数(AsStatic
)或使用变量(AsDynamic
):
Sub loadboat(param$)
MsgBox param
End Sub
Sub AsStatic()
With Sheet1.Range("A1:B2")
With .Parent.Buttons.Add(.Left, .Top, .Width, .Height)
.Caption = "GO!"
.OnAction = "'loadboat ""hello""'"
End With
End With
End Sub
Sub AsDynamic()
Const param$ = "hello"
With Sheet1.Range("A1:B2")
With .Parent.Buttons.Add(.Left, .Top, .Width, .Height)
.Caption = "GO!"
.OnAction = "'loadboat """ & param & """'"
End With
End With
End Sub