TheRedDogg

D&D Roll Die Excel Macro

May 13th, 2018
5,325
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Public Sub rolldie()
  2.  
  3.     On Error GoTo ErrHandler:
  4.    
  5.     Dim showDebug As Boolean
  6.     showDebug = False
  7.    
  8.     Dim numRolls As Integer
  9.     Dim currDieCnt As Integer
  10.     Dim currDieRoll As Integer
  11.     Dim numDie As Integer
  12.     Dim dieSize As Integer
  13.     Dim modifier As Integer
  14.     Dim finalRoll As Integer
  15.     Dim inputArray() As String
  16.     Dim debugStr As String
  17.    
  18.     numRolls = WorksheetFunction.CountA(Selection)
  19.    
  20.     If numRolls = 0 Then Exit Sub
  21.    
  22.     For Each currRoll In Selection.Columns(1).Cells
  23.        
  24.         If InStr(1, LCase(currRoll.Value), "d") = 0 Then GoTo NextIteration
  25.        
  26.         currDieRoll = 0
  27.         finalRoll = 0
  28.         debugStr = ""
  29.        
  30.         inputArray = Split(LCase(Replace(currRoll.Value, " ", "")), "d", 2)
  31.        
  32.         numDie = CInt(inputArray(0))
  33.        
  34.         If InStr(inputArray(1), "+") > 0 Then
  35.             inputArray = Split(inputArray(1), "+", 2)
  36.             dieSize = CInt(inputArray(0))
  37.             modifier = CInt(inputArray(1))
  38.         Else
  39.             dieSize = inputArray(1)
  40.             modifier = 0
  41.         End If
  42.        
  43.         For currDieCnt = 1 To numDie
  44.        
  45.             currDieRoll = CInt(Rnd() * dieSize + 1)
  46.             finalRoll = finalRoll + currDieRoll
  47.            
  48.             If currDieCnt > 1 Then
  49.                 debugStr = debugStr & " + " & CStr(currDieRoll)
  50.             Else
  51.                 debugStr = CStr(currDieRoll)
  52.             End If
  53.            
  54.         Next
  55.        
  56.         If modifier > 0 Then
  57.             finalRoll = finalRoll + modifier
  58.             debugStr = debugStr & " + " & CStr(modifier)
  59.         End If
  60.        
  61.         currRoll.Offset(0, 1).Value = CStr(finalRoll)
  62.        
  63.         If showDebug Then
  64.             currRoll.Offset(0, 2).Value = debugStr
  65.         End If
  66.        
  67. NextIteration:
  68.     Next
  69.    
  70.     Exit Sub
  71.    
  72. ErrHandler:
  73.    
  74.     Set Selection.Offset(0, 1).Value = "Error"
  75.  
  76. End Sub
Advertisement