打印数组结果的活动单元格的VBAfunction

我想写一个函数的结果应该打印/写入一个单元格的数组范围。

活动单元格应该是第一个元素,下一个单元格是第二个元素(等等)。 所以,例如,如果我当前的活动单元格是B2,那么所需的结果应该如下图所示。

我的下面的代码只能在Debug.Pring上工作,但是我不知道如何在Excel工作表上实际使用它。

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 

在这里输入图像说明

在这里输入图像说明

 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 

稍微改变你的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足够的单元格来覆盖整个string:

在这里输入图像说明

然后input你的公式:

 =ShowResults() 

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

在这里输入图像说明

如果做得不错,excel会把{}放在公式的周围。

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

 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