- 1、join函数,将数组(只限一维)用“符号”连接起来。
Sub join1()
Dim arr(), brr()
brr = Array(1, 2, 3, 4, 5, 6)
arr = Array("小明", "爱", "吃", "番", "茄")
s = join(arr, "/")
ss = join(brr, ",")
End Sub
- 结果
- s = "小明/爱/吃/番/茄"
- ss= "1,2,3,4,5,6"
- 当然我们也可以通过遍历循环的方式链接起来,以下代码都能够返回
s ="小明/爱/吃/番/茄" ,但却比使用join要麻烦。
Sub join1()
Dim arr()
arr = Array("小明", "爱", "吃", "番", "茄")
For i = 0 To UBound(arr)
If i = 0 Then
s = arr(0)
Else
s = s & "/" & arr(i)
End If
Next
End Sub
'............................或.............................................
Sub join2()
Dim arr()
arr = Array("小明", "爱", "吃", "番", "茄")
For i = 0 To UBound(arr)
s = s & "/" & arr(i)
Next
s = Mid(s, 2, Len(s) - 1)
End Sub
- 2、split函数,将字符串按某个符合分列成一个字符型string的一维数组。
Sub split2()
s = "小明/爱/吃/番/茄"
a = Split(s, "/")
End Sub
- 因为split生成的是一维数组,因此,可以通过数组索引index引用指定的值。
Sub split2()
s = "小明/爱/吃/番/茄"
a = Split(s, "/")(0)
b = Split(s, "/")(3)
End Sub
- 练习1:将古娜参与的所有项目用“,”链接在一起,放在一个单元格内。
Sub ss()
Dim arr, brr(), i%, k%
arr = Range("A1").CurrentRegion
For i = 2 To UBound(arr) '遍历数组元素
If arr(i, 1) = Range("d1").Value Then '如果姓名等于D1单元格的姓名
k = k + 1 '计数
ReDim Preserve brr(1 To k) '将项目放进数组brr
brr(k) = arr(i, 2)
End If
Next
Range("e1") = join(brr, ",") '将项目链接起来
End Sub
Sub split2()
Dim arr, brr(1 To 1000, 1 To 2), s
'声明brr数组,足够大
arr = [a1].CurrentRegion '将数据放进数组arr
For i = 2 To UBound(arr)
s = Split(arr(i, 2), ",") '项目用split分开,并生成数组
For j = 0 To UBound(s) '遍历split生成的数组,将数据放进数组brr
k = k + 1 '计数
brr(k, 1) = arr(i, 1) '姓名
brr(k, 2) = s(j) '分开的单个' 项目'
Next
Next
[e2].Resize(k, 2) = brr '输出数据到单元格E1
End Sub