新建From1(窗体),新建Command1(按钮CommandButton),代码:
Private Sub Command1_Click()
Dim strA As String
Dim arrA() As Byte
ReDim arrA(10)
strA = "MaNongKu.com"
arrA(0) = 1
arrA(1) = 2
arrA(3) = 3
Debug.Print "Command1 strA=" & strA & " address:" & StrPtr(strA)
Call s_1(strA, arrA())
Debug.Print "Back strA=" & strA & " address:" & StrPtr(strA)
Debug.Print "Back arrA=" & arrA(0) & " " & arrA(1) & " " & arrA(2) & " address:" & VarPtr(arrA(0)) & " " & VarPtr(arrA(1)) & " " & VarPtr(arrA(2))
End Sub
Private Sub s_1(strA As String, arrA() As Byte)
Debug.Print "s_1 strA=" & strA & " address:" & StrPtr(strA)
Debug.Print "s_1 arrA=" & arrA(0) & " " & arrA(1) & " " & arrA(2) & " address:" & VarPtr(arrA(0)) & " " & VarPtr(arrA(1)) & " " & VarPtr(arrA(2))
Call s_2(strA, arrA())
End Sub
Private Sub s_2(strA As String, arrA() As Byte)
Debug.Print "s_2 strA=" & strA & " address:" & StrPtr(strA)
Debug.Print "s_2 arrA=" & arrA(0) & " " & arrA(1) & " " & arrA(2) & " address:" & VarPtr(arrA(0)) & " " & VarPtr(arrA(1)) & " " & VarPtr(arrA(2))
strA = "good"
arrA(0) = 7
arrA(1) = 8
arrA(3) = 9
End Sub
运行结果:
Command1 strA=MaNongKu.com address:228255300
s_1 strA=MaNongKu.com address:228255300
s_1 arrA=1 2 0 address:228433688 228433689 228433690
s_2 strA=MaNongKu.com address:228255300
s_2 arrA=1 2 0 address:228433688 228433689 228433690
Back strA=good address:228253300
Back arrA=7 8 0 address:228433688 228433689 228433690
另外的操作,如果对s_2的strA设置成超过"MaNongKu.com"长度的 "This is a very good website."地址会变成address:228482972。
结论:子程序可以修改参数,字符串地址可能会变,而数组或其它类型不会变(因为是固定长度)。字符串的长度如果小于原始长度,地址不会变,大于则变。(因为如果是小于,内存就直接把结束符0写入原始地址的中间,如果大于原始长度只有开辟新的内存地址释放老地址所以要变)。
联想:把主程序的代码通过子程序和参数甩到子程序不影响速度。
再附加一个例子:
Private Sub Command1_Click()
Dim arrB() As Byte
ReDim arrB(7)
arrB(0) = 65
arrB(1) = 66
Debug.Print VarPtr(arrB(0))
ReDim Preserve arrB(1)
Debug.Print VarPtr(arrB(0))
End Sub
运行结果:
228432320
228432208
经过测试得到结论:只要是ReDim或ReDim Preserve,不管减少还是增加数组大小,地址都会变。