dice notation in excel

有些话、适合烂在心里 提交于 2019-12-06 15:37:01

Say we have dice expressions in column A

Hi-light the cells and run this small macro:

Sub DiceXlator()
    Dim r As Range, v As String, NewForm As String, deemode As Boolean
    Dim dee As String
    dee = "d"
    deemode = False
    For Each r In Selection
        v = r.Value
        NewForm = "="
        For i = 1 To Len(v)
            ch = Mid(v, i, 1)
            If ch = dee Then
                NewForm = NewForm & "*RANDBETWEEN(1,"
                deemode = True
            Else
                If Not IsNumeric(ch) And deemode Then
                    deemode = False
                    NewForm = NewForm & ")"
                End If
                NewForm = NewForm & ch
            End If
        Next i

        If deemode Then
            NewForm = NewForm & ")"
        End If

        r.Offset(0, 1).Formula = NewForm
    Next r
End Sub

The macro translates each dice expression into a standard Excel formula and places the formula in the adjacent cell in column B

Here is a tiny example of inputs/outputs

EDIT#1:

Here is the same logic in the form of a User Defined Function - UDF

Public Function RollDice(r As Range) As Variant
    Application.Volatile
    Dim v As String, NewForm As String, deemode As Boolean
    Dim dee As String
    dee = "d"
    deemode = False
        v = r.Value
        NewForm = "="
        For i = 1 To Len(v)
            ch = Mid(v, i, 1)
            If ch = dee Then
                NewForm = NewForm & "*RANDBETWEEN(1,"
                deemode = True
            Else
                If Not IsNumeric(ch) And deemode Then
                    deemode = False
                    NewForm = NewForm & ")"
                End If
                NewForm = NewForm & ch
            End If
        Next i

        If deemode Then
            NewForm = NewForm & ")"
        End If

        RollDice = Evaluate(NewForm)

End Function

EDIT#2:

It is possible to get Min, Max, and Average in a statistical sense. For example in B1 enter:

=RollDice($A$1)

then copy B2 from B3 thru B1000

and finally use:

=MAX(B1:B1000)
=MIN(B1:B1000)
=AVERAGE(B1:B1000)

I would look at the functions RAND and RANDBETWEEN

Setup a table listing the dice choices 1 roll , 2 rolls etc and use those functions to calculate values from the inputs.

Keep the inputs separate from the table of calculations. Separate input from calculations and Separate output. You can even use different sheets in a workbook.

Don't worry about the notation at first, get the functions working.

Then you can format the output using string CONCATENATE to build up your notation.

Conditional formatting is only used once you have differing values in the excel cells and is probably not applicable here.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!