2017-09-14 48 views
-1

我有一個420字符串,我需要在每個單元格中分成42個字符。 [所以在這種情況下,10個單元格] 但是,如果子字符串打破了一個單詞,該單詞應該溢出到下一個子字符串中。使用VBA拆分文本字符串到相等的子字符串中,以確保沒有字中斷

+2

感謝您告訴我們您要做什麼。如果您在任何時候都有問題,那麼當您首次發佈您的嘗試代碼時,請隨時詢問。 – SJR

+0

使用分割函數:split(「要分割的文本字符串」,「」)獲取單詞,然後檢查相鄰單詞的len並連接,如果Len(a)+ len(B)<= 10 – KacireeSoftware

回答

1

這是一個裸機VBA腳本,將執行此操作。

Sub breakUpSentence() 
    Dim strSentenceIn As String 
    Dim strSentenceOut As String 
    Dim arrWords As Variant 
    Dim strWord As Variant 
    Dim cellWrite As Range 

    'get the sentence 
    strSentenceIn = Sheet1.Range("A1").Value 

    'break it up into words storing the words in an array 
    arrWords = Split(strSentenceIn, " ") 

    'Set the first cell to write out to 
    Set cellWrite = Sheet1.Range("B1") 

    'Iterate through words 
    For Each strWord In arrWords 

     'Add the word to the output sentence, only include a space if the sentence is already populated 
     If strSentenceOut = "" Then strSentenceOut = strWord Else strSentenceOut = strSentenceOut & " " & strWord 

     'If the output sentence is now greater than or equal to 42 characters, then write it out 
     If Len(strSentenceOut) >= 42 Then 

      'Write it out 
      cellWrite.Value = strSentenceOut 

      'Increment to the next cell we want to write to 
      Set cellWrite = cellWrite.Offset(, 1) 

      'Clear the output sentence 
      strSentenceOut = "" 
     End If 

    Next strWord 

End Sub 
0

感謝您的幫助!

有些麻煩,但已經想通了。 [放到原始代碼]

這使用了一個UDF。

splittext(range, part number, maximum allowed number) 

唯一的問題是需要使用多個公式來獲取各個部分。

Sub breakUpSentenceEqualParts() 

Dim strSentenceIn As String 
Dim strSentenceOut As String 
Dim arrWords As Variant 
Dim strWord As Variant 
Dim cellWrite As Range 

strSentenceIn = Sheet1.Range("A1").Value 

arrWords = Split(strSentenceIn, " ") 

Set cellWrite = Sheet1.Range("B1") 

For Each strWord In arrWords 

     If strSentenceOut = "" Then strSentenceOut = strWord Else strSentenceOut = strSentenceOut & " " & strWord 

     If Len(strSentenceOut) >= 42 Then 

     cellWrite.Value = strSentenceOut 

     Set cellWrite = cellWrite.Offset(, 1) 

     strSentenceOut = "" 
    End If 

Next strWord 

End Sub