如何在Excel VBA中截断最多某些字符?

时间:2019-01-28 14:20:04

标签: excel vba excel-formula

我有一个excel表格,在单列中有一些描述行,我的目标是获得一个将通过所有这些描述行的vba,并将其截断到某些字符限制,例如30个字符,如果截断在单词的中间停止在30个字符处,然后我想要完整的单词(在这种情况下,可以延伸超过30个字符)。

我尝试使用下面的VBA代码执行此操作,但是我无法获得所需的内容。

Function foo(r As Range)
Dim sentence As Variant
Dim w As Integer
Dim ret As String

' assign this cell's value to an array called "sentence"
sentence = Split(r.Value, " ")

' iterate each word in the sentence
For w = LBound(sentence) To UBound(sentence)
    ' trim to 6 characters:
    sentence(w) = Left(sentence(w), 6)
Next

' Join the array back to a string/sentence
ret = Join(sentence, " ")

'Make sure the sentence is max 20 chars:
ret = Left(ret, 20)


'return the value to your function expression:
foo = ret
End Function

我希望代码能遍历特定列的所有行,并将其截断为30个字符,如果截断在单词中间停止,则应保留该单词。

5 个答案:

答案 0 :(得分:2)

自从您为公式标记了标签

=LEFT(A1,FIND(" ",A1,30)-1)

答案 1 :(得分:0)

我认为您正在寻找instr()函数。这样可以为您排在第30位之后的第一个空格字符。

您将获得以下信息:

Dim SpacePosition as Integer

'return the position for the first space-character after position 29
SpacePosition = Instr(30, r.value," ")

if SpacePosition <> 0 then

    'fill ret with the substring up to the first space after position 29
    ret = left(r.value, SpacePosition - 1)

else

    'if there is no space-character (after position 29) then take the whole string
    ret = r.value

end if

希望有帮助。

答案 2 :(得分:0)

@scott Craner的最佳和出色解决方案。但是,在您的VBA代码中,您可以更改以下内容以获得所需的结果

'Join the array back to a string/sentence
'ret = Join(sentence, " ")
ret = ""
For w = LBound(sentence) To UBound(sentence)
    ' trim to 6 characters:
    sentence(w) = Left(sentence(w), 6)
ret = ret & IIf(Len(ret) > 0, " ", "") & sentence(w)
If Len(ret) >= 30 Then Exit For
Next w

'Make sure the sentence is max 20 chars:
' ret = Left(ret, 20)

答案 3 :(得分:0)

Public Function foo(r As Range, length As Integer) As String
    If Len(r.Value) <= length Then
        foo = r.Value
    Else
        foo = Left(r.Value, 1 + length)
        foo = RTrim(Left(foo, InStrRev(foo, " ")))
    End If
End Function

我想您想通过传递20作为第二个参数来运行它

答案 4 :(得分:0)

从工作表1的A列开始循环行:

Option Explicit

Sub test()

    Dim Lastrow As Long, i As Long

    With ThisWorkbook.Worksheets("Sheet1")
        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = 1 To Lastrow
        'Insert Code

        Next i

    End With

End Sub