VBA 用于在活动单元格中打印数组结果的函数

VBA function to print array result in active cell

我想写一个函数,结果应该print/write一个数组到一系列单元格中。

活动单元格应该是第一个元素,下面的下一个单元格是第二个(依此类推)。因此,例如,如果我当前的活动单元格是 B2,则所需结果应如下图所示。

我下面的代码仅适用于 Debug.Pring,但我无法弄清楚如何在 excel sheet 上实际使用它。

Function ShowResult()

Dim strArray() As String
Dim result As String
result = "Maybe I think too much but something's wrong"
strArray = Split(result, " ")

Dim StartRow, i As Integer
StartRow = 1

For i = 0 To UBound(strArray)
    Debug.Print strArray(i)
    'Range("A" & i + StartRow).Value = strArray(i) <--I tried even with this, didn't work!
Next
End Function

稍微更改一下函数:

Function ShowResult() As Variant

Dim strArray() As String
Dim result As String
result = "Maybe I think too much but something's wrong"
strArray = Split(result, " ")

For i = 0 To UBound(strArray)
    Debug.Print strArray(i)
    'Range("A" & i + StartRow).Value = strArray(i) <--I tried even with this, didn't work!
Next

ShowResult = Application.Transpose(strArray)
End Function

然后在使用时需要 select 足够的单元格以覆盖整个字符串:

然后输入您的公式:

=ShowResults()

按 Ctrl-Shift-Enter 使其成为数组公式:

如果操作正确 excel 将在公式周围加上 {}

Sub ShowResult()

Dim strArray() As String
Dim result As String
result = Application.InputBox("enter string")

strArray = Split(result, " ")

For I = 0 To UBound(strArray)
    Debug.Print strArray(I)
    Cells(I + 1, 1).Value = strArray(I) 'this puts in in column A. change column here or even prompt user for it?
Next

End Sub

或者,您也可以一次性填充 return 数组并使用数组公式调用它...也许..

Option Explicit

Function ShowResult() As Variant

Dim strArray() As String
Dim Result As String
Dim i As Integer

Result = "Maybe I think too much something's wrong"
strArray = Split(Result, " ")

ReDim vTemp(LBound(strArray) To UBound(strArray), LBound(strArray) To LBound(strArray)) As String
For i = LBound(strArray) To UBound(strArray)
    vTemp(i, LBound(strArray)) = strArray(i)
Next
ShowResult = vTemp

End Function