如何缩短这个VBA代码?

时间:2015-03-18 20:19:50

标签: vba

如何缩短此代码?我希望在循环中缩短If这段代码。我尝试过这样的Me.Controls("x" & t) = 0,但是它返回了一个语法错误。我不知道我能做什么。请帮忙。

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

1 个答案:

答案 0 :(得分:1)

数组是最好的解决方案。首先确定它是一维还是二维然后你可以使用它。我相信你的是一个二维数组。

您可以在数组中将X1设置为X30并获取值。一维和二维数组的模拟代码在这里

1-D数组:

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数组

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)

如果有这方面的帮助,请将其标记为答案(也可以帮助某人)。

此致 摩尼