VBA换行代码上的Excel值错误

时间:2016-04-10 01:00:12

标签: excel vba excel-vba

因此,我一直在尝试创建一个程序,该程序将采用一段文本并将其编辑为每行最多包含50个字符,但也将单词保持在一起(因此替换一行中的最后一个空格)文本换行字符长50个字符)但我继续得到一个值错误作为我的输出!

以下是目前的代码:

Option Explicit

Public Function LnBrk50(selection) As String

    Dim bookmark As Long
    Dim step As Byte
    Dim length As Byte

'finds the last instance number of a space character in the text block within 50 characters
    length = 50 - Len(WorksheetFunction.Substitute(Left(selection, 50), " ", ""))
'replaces the last instance of a space character with a line break character
        selection = WorksheetFunction.IfError(WorksheetFunction.Substitute(selection, " ", vbNewLine, length), selection)
'character number of the last line break in the text block
    bookmark = WorksheetFunction.Find(vbNewLine, selection)

    step = 0
    Do Until step = 9
'finds the last instance number of a space character in the text block within the 50 characters after the last line break
        length = 50 + bookmark - Len(WorksheetFunction.Substitute(Left(selection, 50 + bookmark), " ", ""))
'replaces the space character found in last line with a line break character
        selection = WorksheetFunction.IfError(WorksheetFunction.Substitute(selection, " ", vbNewLine, length), selection)
'adds character number of the last line break
        bookmark = WorksheetFunction.Find(vbNewLine, selection, bookmark + 1)
        step = step + 1
    Loop

End Function

所以如果有人能找到我可能会犯的错误会产生#VALUE!在单个引用的文本单元格上使用时会出错,非常感谢!!

2 个答案:

答案 0 :(得分:0)

此屏幕截图显示单元格A1中的一个非常长的文本字符串。单元格A2包含

=LnBrk50(A1)

enter image description here

以下代码是LnBrk50背后的内容。

Option Explicit

Public Function LnBrk50(ByRef selection As Variant) As String

    Dim tempStr As String
    Dim iLoc As Long, iEnd As Long

    tempStr = selection.Value
    If Len(tempStr) > 50 Then
        iLoc = 0
        Do While Len(tempStr) - iLoc > 50
            iEnd = iLoc + 50
            If Len(tempStr) < iEnd Then iEnd = Len(tempStr)
            If Not InStrRev(tempStr, " ", iEnd) > 0 Then
                iLoc = iLoc + 1
            Else
                iLoc = InStrRev(tempStr, " ", iEnd)
                tempStr = Left(tempStr, iLoc - 1) & vbNewLine & Right(tempStr, Len(tempStr) - iLoc)
            End If
        Loop
    End If
    LnBrk50 = tempStr

End Function

如果您想修改A1而不是将修改后的文本移动到B1,我建议使用子程序并将其附加到按钮而不是使用函数。

答案 1 :(得分:0)

你可以试试这个

Option Explicit

Function LnBrk50(rng As Range, maxChar As Long) As String

Dim strng2 As String, subStrng As String
Dim arr As Variant
Dim i As Long

arr = Split(rng)    
i = 0
Do While i < UBound(arr)
    subStrng = arr(i)
    Do While Len(subStrng) + 1 + Len(arr(i + 1)) <= maxChar
        subStrng = subStrng + " " + arr(i + 1)
        i = i + 1
        If i = UBound(arr) Then Exit Do
    Loop
    strng2 = strng2 & subStrng & IIf(i < UBound(arr), vbCrLf, "")
    i = i + 1
Loop    
LnBrk50 = strng2

End Function

您的函数将被称为

=LnBrk50(A1,50)

可能是最有趣的......