Entering an equation into a single cell is as simple as typing an equal sign and then typing the equation. The equation will continue to be displayed in the cell until the user moves the cursor to another cell; then the LeaveCell event will occur. Listing 13.16 shows the code to achieve this.
Listing 13.16: MSFlexGrid1_LeaveCell Event in Charter
Private Sub MSFlexGrid1_LeaveCell()
If Left(MSFlexGrid1.Text, 1) = “=” Then
Equations(MSFlexGrid1.Row, MSFlexGrid1.Col) = Mid(MSFlexGrid1.Text, 2)
MSFlexGrid1.Text = Compute(Equations(MSFlexGrid1.Row, MSFlexGrid1.Col))
End If
Recalculate
End Sub
The LeaveCell event contains the code that will save contents of the cell into Equations array if the first character of the cell is an equal sign. If so, then it computes a new value for the cell using the Compute function and saves the result in the cell.
Finally, I recalculate the contents of the entire grid using the Recalculate routine. This is done even if there wasn’t an equation in the cell. It’s possible that someone simply typed a new number into the cell, and the cell might be used in an equation somewhere else in the grid. Without recalculating the entire spreadsheet, any cells that use this value in their calculations would display an incorrect value.