ReDim保留结果有误

时间:2017-04-07 21:06:32

标签: excel vba excel-vba

我有一个函数,它将一系列单元格作为参数,并检查这些单元格中有多少包含“2”或“3”,然后给出一个带有确定文本的消息框。 问题在于动态数组。如果我使用固定长度的数组,一切正常。但是一旦我使用ReDim Preserve方法,该函数不会在单元格中返回任何值,也不会显示消息框... 这有什么不对?

Function test2(Var As Range)
          Dim result0 As Integer
          Dim resultsFinal() As Long
          ReDim resultsFinal(0)
          Dim i As Integer

          i = 0

          result = 0

          Dim cell As Range
          For Each cell In Var.Cells
                  If cell.Value = 2 Or cell.Value = 3 Then
                         result = result + 1
                         ReDim Preserve resultsFinal(result)
                         resultsFinal(i) = cell.Row
                         i = i + 1
                         test2 = cell.Value
          End If
          Next cell

          MsgBox result & "and  " & vbNewLine &   
          array: " & Join(resultsFinal, ", ")

End Function

1 个答案:

答案 0 :(得分:1)

JOIN命令仅适用于字符串或变体。

如果您更改为STRING并修复了几个拼写错误,则可以正常使用

Function test2(Var As Range)
  Dim result As Integer
  Dim resultsFinal() As String
  ReDim resultsFinal(0)
  Dim i As Integer

  i = 0

  result = 0

  Dim cell As Range
  For Each cell In Var.Cells
          If cell.Value = 2 Or cell.Value = 3 Then
                 result = result + 1
                 ReDim Preserve resultsFinal(result)
                 resultsFinal(i) = cell.Row
                 i = i + 1
                 test2 = cell.Value
  End If
  Next cell

  MsgBox result & "and  " & vbNewLine & " array: " & Join(resultsFinal, ", ")
End Function