Module Module1
Sub main()
Dim pl(), pll() As Integer
Dim a, b As Integer
ReDim pl(0)
ReDim pll(0)
Do
a = InputBox("insert number:")
If a <> 0 Then
b = b + 1
ReDim Preserve pl(b)
pl(b) = a
End If
Loop Until a = 0
pll = **se(pl)**
End Sub
Function se(pol()) As Integer()
Dim r, t, w, m As Integer
Dim fix() As Integer
ReDim fix(0)
r = UBound(pol)
w = 2
For t = 1 To r
For m = 1 To r
If w <= r Then
If pol(w) < pol(t) Then
ReDim Preserve fix(t)
fix(t) = pol(w)
End If
End If
w = w + 1
Next
Next
se = fix
End Function
结束模块
嗨,我创建了这个函数(不知道它是否工作)se(pl)取数字数组并以升序返回该数组。但是当我想将该函数分配到数组中时 - pll = se(pl)它会给我这个错误==&gt; “整数类型的值不能转换为对象,因为整数不是引用类型”
对不起,我有人帮忙吗?
答案 0 :(得分:0)
你要同时标记&#34; VBA&#34;和#34; Visual Studio&#34;但接下来仅适用于VBA
关于你的代码我使它工作(意味着它运行到最后没有错误)只能用fix
代替fixed
,因为我的Excel VBA&#34;编译器&#34;抛出&#34;语法错误&#34;消息由于存在&#34; FIX()&#34; VBA功能。
所以,在调用了替换Function se
之后,它返回了一个没有问题的整数数组。
但它并没有按照你所说的那样做,即:&#34;按升序返回传递的数组&#34;。
另外,变量声明和输入过程都允许传递字符串。
所以这里遵循我的建议让你的代码做你所说的你需要的事情(&#34;以递增的顺序返回传递的数组&#34;),并使用更强大的输入程序
Option Explicit
Sub main()
Dim pl() As Integer, pll() As Integer
pl = TryConvertToInt(Split(InputBox("insert numbers (separated by space):")))
pll = se(pl)
End Sub
Function TryConvertToInt(arr As Variant) As Integer()
Dim i As Long, n As Long
ReDim myint(1 To UBound(arr) - LBound(arr) + 1) As Integer
For i = LBound(arr) To UBound(arr)
If IsNumeric(arr(i)) And arr(i) <> 0 Then
n = n + 1
myint(n) = CInt(arr(i))
End If
Next i
ReDim Preserve myint(1 To n) As Integer
TryConvertToInt = myint
End Function
Function se(pol() As Integer) As Integer()
'adapted from https://support.microsoft.com/en-us/kb/133135
Dim Temp As Integer
Dim i As Integer
Dim NoExchanges As Boolean
Dim fixed() As Integer
ReDim fixed(1 To UBound(pol) - LBound(pol) + 1)
fixed = pol
' Loop until no more "exchanges" are made.
Do
NoExchanges = True
' Loop through each element in the array.
' For i = 1 To UBound(pol) - 1
For i = LBound(fixed) To UBound(fixed) - 1
' If the element is greater than the element following it, exchange the two elements.
If fixed(i) > fixed(i + 1) Then
NoExchanges = False
Temp = fixed(i)
fixed(i) = fixed(i + 1)
fixed(i + 1) = Temp
End If
Next i
Loop While Not (NoExchanges)
se = fixed
End Function
你可以看到:
main
sub现在非常简单,简化为三个语句
第二个陈述包含三个电话:
InpuBox
函数的调用,其中要求用户输入由空格分隔的所有想要的数字(并且不需要零来关闭序列)Split
函数的调用,让它将输入字符串解析为由空格分隔的字符串数组组成的字符串数组TryConvertToInt
函数,负责分析字符串数组并将其转换为整数数组,只允许零以外的数字第三个语句调用se
函数并将其返回整数数组放入pll
整数数组
se
函数具有从https://support.microsoft.com/en-us/kb/133135派生的排序算法,仅适用于处理整数数组。
有了这样的结构,你现在可以更有效地编码了,因为你可以专注于main
sub来做&#34; main&#34;通过调用特定的子和/或函数来做(做,做,...)。
这离开&#34;非主要&#34;适用于特定的子或函数,专注于特定目的:例如,您可能希望自定义TryConvertToInt
函数以获取更详细的过滤操作