Can anyone suggest why the following code is returning an error: "Run-time error '9': Subscript out of range" ? I have highlighted in RED, the code that is causing the problem - it is this part: Range("P" & i).Value = arr(j, 1)
Any help would be appreciated.
Sub STR_UPu2_2_H()
' Declare variables
Dim i As Long, j As Long, n As Long
Dim arr() As Variant, dict As Object
' Initialize dictionary object
Set dict = CreateObject("Scripting.Dictionary")
' Get total number of rows that meet the given conditions
n = Application.WorksheetFunction.CountIfs(Range("B27:B142"), "Strength", Range("K27:K142"), "U-PL-1", Range("L27:L142"), 1, Range("M27:M142"), "H")
' Resize array to hold the random numbers
On Error Resume Next
ReDim arr(1 To n, 1 To 1)
On Error GoTo 0
' Generate unique random numbers
For i = 1 To n
Do
j = Int(Rnd() * n) + 1
Loop While dict.Exists(j)
dict(j) = True
arr(i, 1) = j
Next i
' Write the random numbers to the range P27:P142
j = 1
For i = 27 To 142
If Range("B" & i) = "Strength" And Range("K" & i) = "U-Pu-2" And Range("L" & i) = 2 And Range("M" & i) = "H" Then
Range("P" & i).Value = arr(j, 1)
j = j + 1
End If
Next i
' Cleanup
Set dict = Nothing
End Sub
Any help would be appreciated.
Sub STR_UPu2_2_H()
' Declare variables
Dim i As Long, j As Long, n As Long
Dim arr() As Variant, dict As Object
' Initialize dictionary object
Set dict = CreateObject("Scripting.Dictionary")
' Get total number of rows that meet the given conditions
n = Application.WorksheetFunction.CountIfs(Range("B27:B142"), "Strength", Range("K27:K142"), "U-PL-1", Range("L27:L142"), 1, Range("M27:M142"), "H")
' Resize array to hold the random numbers
On Error Resume Next
ReDim arr(1 To n, 1 To 1)
On Error GoTo 0
' Generate unique random numbers
For i = 1 To n
Do
j = Int(Rnd() * n) + 1
Loop While dict.Exists(j)
dict(j) = True
arr(i, 1) = j
Next i
' Write the random numbers to the range P27:P142
j = 1
For i = 27 To 142
If Range("B" & i) = "Strength" And Range("K" & i) = "U-Pu-2" And Range("L" & i) = 2 And Range("M" & i) = "H" Then
Range("P" & i).Value = arr(j, 1)
j = j + 1
End If
Next i
' Cleanup
Set dict = Nothing
End Sub