如何将2D数组传递给过程,并在函数内部对其进行修改? VBA

时间:2018-07-07 16:27:05

标签: arrays vba word-vba

使用VBA创建Word宏我遇到以下问题:

我正在尝试使用函数填充2d数组。问题是,当我尝试将2D数组传递给函数时,出现以下错误:

  

类型不匹配的数组或预期的用户定义类型

我的宏:

Sub Tests()
'
' Tests Macro
'
Dim paragraphs(21, 1) As String
populate_paragraph (paragraphs)
End Sub

调用过程:

Sub populate_paragraph(replacers() As String)

ReDim replacers(21, 1) As String

replacers(0, 0) = "%HEADER%"
replacers(1, 0) = "%DESIGN_BRIEF_PARAGRAPH%"
...
replacers(21, 0) = "%DISCLAIMER_PARAGRAPH%"

replacers(0, 1) = create_header
replacers(1, 1) = create_design_brief_paragraph
...
replacers(21, 1) = create_disclaimer_paragraph

End Sub

如果我没有将2D数组传递给过程,而是尝试使用函数的返回值对其进行初始化,则会出现以下错误:

  

无法分配给数组

在这种情况下的代码是:

Sub Tests()
'
' Tests Macro
'
Dim paragraphs(21, 1) As String
paragraphs = populate_paragraph
End Sub

调用函数:

Function populate_paragraph() As String

Dim replacers(21, 1) As String

replacers(0, 0) = "%HEADER%"
replacers(1, 0) = "%DESIGN_BRIEF_PARAGRAPH%"
...
replacers(21, 0) = "%DISCLAIMER_PARAGRAPH%"

replacers(0, 1) = create_header
replacers(1, 1) = create_design_brief_paragraph
...
replacers(21, 1) = create_disclaimer_paragraph

populate_paragraph = replacers

End Function

感谢您阅读我的问题并为您提供帮助

1 个答案:

答案 0 :(得分:2)

这很棘手...

您必须传递数组ByRef,因为您正在调用的过程中对其进行了更改,而这不是函数,因此可以将其传递回。在这种特定情况下,VBA坚持传递值ByRef

与此相关的是,您将要传递的参数放在括号中:(paragraphs())。由于参数是传递给“方法”而不是函数,因此不应使用括号。如果这样做,您是在告诉VBA您要传递参数ByVal

以下作品:

Sub Tests()
  Dim paragraphs(21, 1) As String

  populate_paragraph paragraphs()
End Sub

Sub populate_paragraph(ByRef replacers() As String)

  ReDim replacers(21, 1) As String
 'etc.

End Sub