Excel VBA将字符串拆分为矩形单元格

时间:2015-02-08 12:16:54

标签: excel vba

我的程序有两个输入框。首先得到一个字符串,然后获得一个矩形尺寸,并将字符串字符拆分为矩形单元格 例如:
字符串输入可以是:"美国。政府计划宰杀11000只俄勒冈州的鸟类以拯救鲑鱼。
矩形的尺寸可以是:6 * 9
结果应该是:

  A B C D E F G H I J 
1 u . s . g o v e r n 
2 m e n t p l a n s t 
3 o c u l l 1 1 0 0 0
4 o r e g o n b i r d 
5 s t o s a v e s a l 
6 m o n

如果你能解决这个问题,我将不胜感激。

3 个答案:

答案 0 :(得分:1)

你在......:

Sub Solution()

    Dim intVer As Integer
    Dim intHor As Integer

    intVer = 6
    intHor = 10

    Dim strTxt As String
    strTxt = "U.S. government plans to cull 11000 Oregon birds to save salmon"
    'remove spaces
    strTxt = Replace(strTxt, " ", "")

    Dim Cell As Range
    Dim i As Integer
    For Each Cell In Range("A1").Resize(intVer, intHor)
        i = i + 1
        Cell = Mid(strTxt, i, 1)
    Next

 End Sub

答案 1 :(得分:0)

你去吧。 Dim1Dim2是您的维度。

Sub Test()
Dim Str As String
Dim Dim1 As Integer: Dim1 = 9
Dim Dim2 As Integer: Dim2 = 6
Dim Counter As Integer: Counter = 1
Str = "U.S. government plans to cull 11000 Oregon birds to save salmon"
Str = Replace(Str, " ", "")
For Each cell In Range("a1", Converttoletter(Dim1) & Dim2).Cells
cell.Value = Mid(Str, Counter, 1)
Counter = Counter + 1
Next
End Sub

Function ConvertToLetter(I As Integer) As String
Converttoletter = Chr(96 + I)
End Function

答案 2 :(得分:0)

考虑:

Sub MAIN()
    Dim s As String, r As Range
    s = "Now is the time for all good men to come to the aid of their country."
    Set r = Range("A1:G30")
    Call Fracture(s, r)
End Sub


Sub Fracture(st As String, rng As Range)
    Dim r As Range
    Dim L As Long, i As Long
    L = Len(st)
    i = 1
    For Each r In rng
        r.Value = Mid(st, i, 1)
        i = i + 1
        If i > L Then Exit Sub
    Next r
End Sub