Tuesday, February 26, 2013

VBA: Intro to Userforms

Tips and Pointers:

  1. Creating a new form: On the Insert Menu, Click Userform.
  2. You can change name or label of userform in its Properties section. 
  3. A form that choose a matrix or data from excel sheet: RefEdit in Toolbox. If there is no RefEdit, Right click on ToolBox--> Additional Controls --> Check refedit.ctrl --> Ok.
  4. Double click on the object itself to view Code. OR On the Project Box, Forms folder, Right click on the form and select View Code.
  5. To get the range in refedit: NewName = Range(RefeditName.Text)
  6. To run the userform:  FormName.show
  7. To end the userform: Unload Me
Additional New Codes:
  1. Sheets.Add => adding new Sheets
  2. Range("A5").Activate => activating the range
Example Process:
Given two matrices of unknown dimensions, we want to multiply them. 

1. Using the Button "Multiply!" in Excel, it opens up the Userform for Matrix Multiplication.
2. Select the two Matrix to multiply.
3. Click Ok, and then the answers will appear in a new sheet.
4. If wrong dimensions, a msgBox will appear.
5.Clicking the Cancel Button will end the Userform.



Code: userform mmult.xlsm


Sub Macro1()
    'For Button Multiply!
    MatrixMult.Show
End Sub


Private Sub CancelBut1_Click()
    Unload Me
End Sub

Private Sub OkBut1_Click()

    MatrixA = Range(mA.Text)
    MatrixB = Range(mB.Text)
    
    'Checker
    If UBound(MatrixA) = UBound(MatrixB) And UBound(MatrixA, 2) = UBound(MatrixB, 2) Then

        'Start of MMult
        r = UBound(MatrixA)
        c = UBound(MatrixA, 2)
    
        Sheets.Add
        ActiveCell.Range("A1").Select
        ActiveCell.Range(Cells(1, 1), Cells(r, c)) = Application.WorksheetFunction.MMult(MatrixA, MatrixB)
    Else
        MsgBox "Wrong dimensions of matrices"
    End If
    
End Sub

No comments:

Post a Comment