lolzzz
lolzzz

Reputation: 13

How to shorten this VBA code?

How can I shorten this code? I want to make this code with If shorter in loop. I tried do something like this Me.Controls("x" & t) = 0 , but it's returning a syntax error. I don't know what I can do. Please help.

x = CStr(Int(Rnd() * 16))
Dim x1 As Byte = 0
...
Dim x30 As Byte = 0

For t = 0 To 15
If x = t And x1 = 0 Then
...
End If
If x = t And x2 = 0 Then
...
End If
...
If x = t And x30 = 0 Then
...
End If

Upvotes: 0

Views: 140

Answers (1)

Manivannan KG
Manivannan KG

Reputation: 371

Array are the best solution. First decide whether its one or two dimensional and then you can use it. I beleive yours is a two dimensional array.

You can set X1 to X30 in array and fetch the values. A mock code for both one and two dimensional array is here

1-D Array:

Dim Films(1 To 5) As String

 Films(1) = "Lord of the Rings"
 Films(2) = "Speed"
 Films(3) = "Star Wars"
 Films(4) = "The Godfather"
 Films(5) = "Pulp Fiction"

 MsgBox Films(4)

2-D Array

Dim Films(1 To 5, 1 To 2) As String
Dim i As Integer, j As Integer

For i = 1 To 5
     For j = 1 To 2
         Films(i, j) = Cells(i, j).Value
     Next j
Next i

 MsgBox Films(4, 2)

Please mark it as answer if this help(can help someone too).

Regards, Mani

Upvotes: 1

Related Questions