请教一个VB数组问题:

来源:百度知道 编辑:UC知道 时间:2024/06/28 14:45:27
Dim a() As String
Dim i As Long, j As Long, y As Long
Dim tmp As String
a = Split(Text2.Text, vbCrLf)

y = UBound(a)

Print y
For i = 1 To UBound(a) - 1
For j = i + 1 To UBound(a)
If GetValue(a(i)) < GetValue(a(j)) Then
tmp = a(i)
a(i) = a(j)
a(j) = tmp
End If
Next
Next

Text2.Text = Join(a, vbCrLf)

End Sub

Function GetValue(ByVal s As String) As Double
GetValue = Val(Split(a, Chr(32))(1))
End Function
这段代码是从文本框2中提出
18 0.750
17 0.600
16 0.500
15 0.571
14 0.500
13 0.444
12 0.400
11 0.545
一组数(这组数是变量,不只这么多)排序,为什么运行时会出错显示下标界
在GetValue = Val(Split(a, Chr(32))(1))这段代码上。请看一下错在哪里,谢谢!

这是我给你的代码吧?是要按数据空格后面的值排序,对吧?

1.GetValue中修改GetValue = Val(Split(a, Chr(32))(1))为:
GetValue = Val(Split(s, Chr(32))(1))

2.要保证你文本中的格式: 18 0.750 中间只有一个空格,你给的数据测试的时候有二个空格

所以保险起见GetValue如下下修改:

Function GetValue(ByVal s As String) As Double
'先处理一下s,去掉连续空格
s=trim(s)
while instr(s,space(2))
s=replace(s,space(2),space(1))
wend
GetValue = Val(Split(s, Chr(32))(1))
End Function

当然如果你的数据全都是2个连续空格,直接:
Function GetValue(ByVal s As String) As Double
GetValue = Val(Split(trim(s), space(2))(1))
End Function

再多说二句,其实要尽力去理解代码,问题就好解决,GetValue这个函数的目的,就是将如“18 0.750”这样的数据,空格后面的数值提取出来,方法太多了,如下也行:

Function GetValue(ByVal s As String) As Double
s=trim(s)
GetValue = val(mid(s, instr(s,space(1))))
End Function

Function GetValue(ByVal s As String) As Double
GetValue = Val(Split(a, Chr(32))(1))
End Function