我有一个420字的字符串,我需要在每个单元格中分成42个字符。 [所以在这种情况下10个细胞] 但是如果子串打破了一个单词,那么该单词应该溢出到下一个子串中。
答案 0 :(得分: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
答案 1 :(得分:0)
如何将字符串拆分为单词数组usind blank作为分隔符和split函数?
https://msdn.microsoft.com/de-de/library/6x627e5f(v=vs.90).aspx
然后遍历数组,根据每个值的长度决定做什么。
答案 2 :(得分: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