如何为两个不同的用户窗体编写通用流程?
How can I write common process for two different userforms?
我创建了两个用户表单。他们都做一些共同的过程。用户窗体 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
感谢您的帮助!
从中创建一个函数,然后将参数传递给它:
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
您可能需要稍微调整一下才能让它完全按照您的意愿行事...但这至少应该给您一个开始...
我创建了两个用户表单。他们都做一些共同的过程。用户窗体 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
感谢您的帮助!
从中创建一个函数,然后将参数传递给它:
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
您可能需要稍微调整一下才能让它完全按照您的意愿行事...但这至少应该给您一个开始...