2016-04-08 64 views
0

我想寫一個函數其中結果應該打印/寫入數組到單元格範圍內。VBA函數打印陣列結果在活動單元格

活動單元格應該是第一個元素,下一個單元格是第二個元素(等等)。因此,例如,如果我當前的活動單元格是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 

enter image description here

enter image description here

+0

'範圍( 「B」 &I + STARTROW)'什麼是'startRow'?如果爲0,則從單元格B0開始,這是無效的。 – findwindow

+0

謝謝@findwindow我只是在代碼中修復它。忽略最初的一個。說它是一列。謝謝 – adhg

+0

單元格A0仍然無效。這是問題所在的行XD Edit:在循環之前添加'StartRow = 1'。但是你會錯過數組的第一個元素,而不是'strArray(i)'do'strArray(startrow-1)'。 – findwindow

回答

3
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 
+0

你將如何從函數中調用它(你能做到嗎?!) – adhg

+0

@adhg你需要應用鍵盤快捷方式或按鈕。 –

+0

哦...知道了!謝謝 – adhg

7

更改功能一點:使用時,您需要選擇足夠的細胞,它會覆蓋整個字符串

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 

然後:

enter image description here

然後鍵入您的公式:

=ShowResults() 

按Ctrl-Shift鍵輸入,使其成爲一個數組公式:

enter image description here

如果處理得當,Excel將放在{}周圍的公式。

+0

+1。如果我不知道範圍(可以是1或1000),我會簡化我的問題。 – adhg

+0

@adhg對於這個XD使用一個函數很麻煩使用一個'sub'代替。 – findwindow

0

或者,你也可以填充返回的數組中一氣呵成,並使用數組公式...也許稱它爲..

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 
+0

btw,注意數組的第二維使用lbound兩次:) – PaulG

+0

......哦,還有,就像旁邊一樣,你也可以調整數組的大小公式爲您要返回的數組的大小。你必須做的是調整到1單元格,然後調整第一維度的大小的數據和使用範圍.FormulaArray。 – PaulG