VBA通过引用和修改内容传递数组 [英] VBA Pass Array By Reference and Modify Contents

查看:145
本文介绍了VBA通过引用和修改内容传递数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

VBA问题。我使用它来制作Solidworks宏,但这并不重要。



有人可以解释传递数组的语法(1维Double类型,长度为三)到一个子程序或功能,所以我可以修改内容。我知道他们必须通过参考传递。我说的是确切的语法,因为我尝试的所有事情都会在子程序/函数调用中出现类型不匹配错误。

我正在寻找的是对Doubles数组正确的Dim语句,初始化语句使所有数组值为零,然后调用子例程调用语句和子例程头我会需要。如果我需要使用变体类型或动态数组,请详细说明,即使我已经知道数组的类型和大小。使用一个函数或一个子,我不在乎哪一个。



我的代码现在工作正常,但我厌倦了避免函数和子例程调用,当我使用数组。我在这里看过无数的文档和类似的问题,但我无法弄清楚。

解决方案

这是相当简单的,例如如下所示:

  Option Explicit 
Sub foo()
Dim myArray(1 To 3)As Double'数组初始化为零值

Call bar(myArray)

MsgBox myArray(3)

结束Sub

Sub bar(ByRef dblArray()As Double)

dblArray(1)= 123
dblArray(2)= 345
dblArray(3)= 33456

End Sub


VBA question. I'm using it to make Solidworks macros, but that's not important.

Can someone explain the syntax to pass an array (1-Dimensional of type Double, with length of three) to a subroutine or function so I can modify the contents. I know that they have to be passed by reference. I'm talking exact syntax, because everything I try I get type mismatch error on the subroutine/function call.

All I'm looking for is the correct Dim statement for the array of Doubles, initialize statement to make all array values zero, then the subroutine call statement and subroutine header that I would need. Please be specific if I need to use variant type or dynamic array, even when I already know the type and size of the array. Use a function or a sub, I don't care which.

My code works fine as of now, but I'm tired of avoiding function and subroutine calls when I'm using arrays. I've looked at countless documentation and similar questions on here, but I just cannot figure it out. Thanks a lot.

解决方案

This is fairly trivial, example as follows:

Option Explicit
Sub foo()
    Dim myArray(1 To 3) As Double  'The array is initialized with zero-values 

    Call bar(myArray)

    MsgBox myArray(3)

End Sub

Sub bar(ByRef dblArray() As Double)

    dblArray(1) = 123
    dblArray(2) = 345
    dblArray(3) = 33456

End Sub

这篇关于VBA通过引用和修改内容传递数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆