Vba 设置一组字符长度后,将换行符插入最近的空格

Vba 设置一组字符长度后,将换行符插入最近的空格,vba,excel,Vba,Excel,我遇到过这段代码(不是我的),它实际上是在确定字符长度后插入换行符 Public Function LFNearSpace(InputStr As String, CharCnt As Long) Dim SplitStrArr() As Variant Dim SplitCnt As Long Dim c As Long Dim i As Long Dim Lcnt As Long Dim Rcnt As Long Dim OutputStr As String 'Split string

我遇到过这段代码(不是我的),它实际上是在确定字符长度后插入换行符

Public Function LFNearSpace(InputStr As String, CharCnt As Long)

Dim SplitStrArr() As Variant
Dim SplitCnt As Long
Dim c As Long
Dim i As Long
Dim Lcnt As Long
Dim Rcnt As Long
Dim OutputStr As String

'Split string into Array
ReDim SplitStrArr(Len(InputStr) - 1)
For i = 1 To Len(InputStr)
    SplitStrArr(i - 1) = Mid$(InputStr, i, 1)
Next

SplitCnt = 0
For c = LBound(SplitStrArr) To UBound(SplitStrArr)
    SplitCnt = SplitCnt + 1
    If SplitCnt = CharCnt Then
        'get count to space nearest to the left and right of word
        For i = c To LBound(SplitStrArr) Step -1
            If SplitStrArr(i) = " " Then
                Lcnt = i
                Exit For
            End If
        Next i
        For i = c To UBound(SplitStrArr)
            If SplitStrArr(i) = " " Then
                Rcnt = i
                Exit For
            End If
        Next i
        'add line feed to nearest space
        If (Rcnt - c) < (c - Lcnt) Then
            SplitStrArr(Lcnt) = Chr(10)
            SplitCnt = c - Lcnt
        ElseIf (Rcnt - c) = (c - Lcnt) Then
            SplitStrArr(Rcnt) = Chr(10)
            SplitCnt = c - Rcnt
        End If
    End If
Next c

'Finalize the output into a single string
LFNearSpace = Join(SplitStrArr, "")

End Function

有什么想法吗?谢谢你试试这个

With Columns(1)
    .ColumnWidth = 75
    .Font.Name = "Arial"
    .Font.Size = 9
    .WrapText = True
End With

下面的代码将在20个字符后出现空格时将字符串分隔为两行

dim inputstr as string = "This is my test input string. I hope it helps!"
dim breakafter as integer= 20
dim line1 as string,line2 as string
dim found as integer=InStr(breakafter, inputstr, " ", vbTextCompare) ' KNOW WHERE IS 1st space after 20 char(s)
line1= Left(inputstr,found )  ' get 1st part of text
line2 =  Replace(inputstr, " ", environment.newline() , found, 1, vbTextCompare) ' get remaining text 
msgbox line1 + iif(isnothing(line2),"",line2)

为什么不能将第1列格式化为换行文本?我这样做了,但我想消除应用自动调整和换行时产生的额外空格,所以我添加了换行符以控制打印时的输出
dim inputstr as string = "This is my test input string. I hope it helps!"
dim breakafter as integer= 20
dim line1 as string,line2 as string
dim found as integer=InStr(breakafter, inputstr, " ", vbTextCompare) ' KNOW WHERE IS 1st space after 20 char(s)
line1= Left(inputstr,found )  ' get 1st part of text
line2 =  Replace(inputstr, " ", environment.newline() , found, 1, vbTextCompare) ' get remaining text 
msgbox line1 + iif(isnothing(line2),"",line2)