Search code examples
excelvbauserform

How can I write common process for two different userforms?


I have created two userforms. They both do some common processes. Userform A checks each row of an Excel worksheet, and goes on adding even numbers. Userform B checks each row of an Excel worksheet, and goes on multiplying even numbers. Checking whether the number in each row is an even number is the common part. Instead of writing the common process twice, can I just write it once and access it from both userforms?

I have to use the similar process for a more complex function later, but I want to try it out with the simplest code first.

Here is my code:

'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

I appreciate your help!


Solution

  • Make a function out of it and then pass a parameter to it:

    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
    

    Then you can call that function from each form like this

    Userform A

    Private Sub ButtonAdd_Click()
      msgbox GetResult(0)
    End Sub
    

    Userform B

    Private Sub ButtonMultiply_Click()
      msgbox GetResult(1)
    End Sub
    

    You may need to tweak it a bit to get it to do exactly what you want... but that should at least give you a start...