VBA – Excel:将string拆分到不同的列中

我想让我的excel文件的用户在单元格“B2”中input一个句子,然后有一个Sub来parsing不同列中的句子(从D2到Dn)。 因此,例如,如果在B2中键入“aaa bbb ccc ddd”,则应该有如下结果:
D2:aaa
D3:bbb
D4:ccc
D5:ddd

我发现如何使用拆分函数分割与VBA的句子,但我很难填充列D,因为我不知道如何定义最后一行(Dn)。 这是我目前使用的:

Sub splitAddress() Dim strAddress As String strAddress = Range("B2").Value Range("D2:D9").Value = WorksheetFunction.Transpose(Split(strAddress, " ")) End Sub 

我想修改“D2:D9”,因为D9并不总是最后一列。 如何写,它应该填充从D2到Dn根据我的B2单元格中的单词数量? 提前致谢 !

有可能是更优雅的方法来做到这一点,但如果你将地址分割成一个数组,你可以使用Ubound获得数组中元素的数量,并使用.Resize来增加范围内的行数:

 Sub splitAddress() Dim strAddress As String Dim strAddressParts() As String Dim numParts As Integer strAddress = Range("B2").Value strAddressParts = Split(strAddress, " ") numParts = UBound(strAddressParts) + 1 Range("D2").Resize(numParts).Value = WorksheetFunction.Transpose(strAddressParts) End Sub 

像下面的循环会为你做:

 Sub splitAddress() Dim i As Integer, x As Integer Dim c As Range i = 0 x = 1 Set c = Range("A5") i = InStr(c.Value, " ") c.Offset(0, x).Value = Left(c.Value, i - 1) x = x + 1 i = InStr(i, c.Value, " ") Do Until InStr(i + 1, c.Value, " ") = 0 c.Offset(0, x).Value = Mid(c.Value, i + 1, InStr(i + 1, c.Value, " ") - i) i = InStr(i + 1, c.Value, " ") x = x + 1 Loop End Sub