我创建了两个用户表单。它们都执行一些通用的过程。用户窗体A检查Excel工作表的每一行,然后继续添加偶数。用户窗体B检查Excel工作表的每一行,然后继续乘以偶数。常见的做法是检查每行中的数字是否为偶数。 不用编写两次通用过程,我可以只编写一次并从两个用户表单中访问它吗?
稍后,我必须对更复杂的功能使用类似的过程,但是我想首先使用最简单的代码进行尝试。
这是我的代码:
'Userform A
Private Sub ButtonAdd_Click()
Dim row As Integer
Dim result1 As Integer
Dim val As Integer
For row = 1 To 10
val = Cells(row, 1).Value
If val Mod 2 = 0 Then result1 = result1 + val
Next row
MsgBox (result1)
End Sub
'Userform B
Private Sub ButtonMultiply_Click()
Dim row As Integer
Dim result2 As Integer
Dim val As Integer
result2 = 1
For row = 1 To 10
val = Cells(row, 1).Value
If val Mod 2 = 0 Then result2 = result2 * val
Next row
MsgBox (result2)
End Sub
感谢您的帮助!
答案 0 :(得分:0)
使用函数,然后将参数传递给它:
Public Function GetResult(result as Integer)
' this function should be in a module so that both forms can see it
Dim row As Integer
Dim result2 as Integer
Dim val As Integer
If result = 1 Then result2 = 1
For row = 1 To 10
val = Cells(row, 1).Value
If result = 0 Then
If val Mod 2 = 0 Then result2 = result2 + val
Else
If val Mod 2 = 0 Then result2 = result2 * val
End If
Next row
GetResult = result2
End Function
然后您可以从每种形式调用该函数
用户表单A
Private Sub ButtonAdd_Click()
msgbox GetResult(0)
End Sub
用户表单B
Private Sub ButtonMultiply_Click()
msgbox GetResult(1)
End Sub
您可能需要对其进行一些微调才能使其完全按照您想要的方式工作...但这至少应该给您一个开始...