• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

# 数据学习系列1-VBA数组和循环语句（3）

1周前 (07-21) 7次浏览

``````Sub FavoriteCities2()
'now declare the array
Dim cities(6) As String
Dim city As Variant
'assign the values to array elements
cities(1) = "Baltimore"
cities(2) = "Atlanta"
cities(3) = "Boston"
cities(4) = "Washington"
cities(5) = "New York"
cities(6) = "Trenton"
'display the list of cities in separate messages
For Each city in cities
MsgBox city
Next
End Sub
``````

1.  在当前模块里，输入下述两个过程：

``````Sub FavoriteCities3()
'now declare the array
Dim cities(6) As String
'assign the values to array elements
cities(1) = "Baltimore"
cities(2) = "Atlanta"
cities(3) = "Boston"
cities(4) = "Washington"
cities(5) = "New York"
cities(6) = "Trenton"
'call another procedure and pass the array as argument
Hallo cities()
End Sub
Sub Hallo (cities() As String)
Dim counter As Integer
For counter = 1 to 6
MsgBox "Hello " & cities(counter)
Next
End Sub
``````

2.  运行过程FavoriteCities3。将一个子过程的数组成员传递给另一个子过程或者函数过程让你可以在许多过程里使用相同的数组，而不需要重复的程序代码。

``````Sub Lotto()
Const spins = 6
Const minNum = 1
Const maxNum = 51
Dim t As Integer ‘looping variable in outer loop 外部循环变量
Dim i As Integer ‘looping variable in inner loop 内部循环变量
Dim myNumbers As String ‘string to hold all picks 储存选号的字符串
Dim lucky(spins) As String ‘array to hold generated picks 储存产生的选号的数组
myNumbers = ""
For t = 1 To spins
Randomize
lucky(t) = Int((maxNum-minNum+1) * Rnd )+ minNum)
'see if this number was picked before 检查本数字是否之前被选出来过
For i = 1 To (t-1)
If lucky(t)=lucky(i) Then
lucky(t) = Int((maxNum–minNum+1) * Rnd)+ minNum) i = 0
End If
Next i
MsgBox "Lucky number is " & t & lucky(t)
myNumbers = myNumbers & " –" & lucky(t)
Next t
MsgBox "Lucky numbers are " & myNumbers
End Sub
``````

Randomize语句将随机数字发生器初始化。指令Int((maxNum-minNum+1) * Rnd + minNum)使用函数Rnd来产生一个在minNum和maxNum之间的随机数值。函数Int将随机数转变为一个整数。除了给minNum和maxNum赋予常量之外，你也可以使用函数InputBox从用户那里获得数据。

内部For…Next循环确保每个选出的数字是唯一的——它不能是之前选出的任何一个数字。如果你忽略了内部循环并且多次运行该过程，你很可能看到重复的号码。