我想删除超过 255 个字符的字符串部分,同时保持单元格中的格式相同。该问题与 this 有关 - 提供的答案不涵盖超过 255 个字符的文本,但由于该问题是独立的,我认为它值得单独提出问题。
出于演示目的,我想从以下文本末尾删除“lobortis”。
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam vulputate tellus enim, at sagittis felis lobortis at. Sed porttitor porttitor congue. Integer a ornare ante. Mauris a pellentesque tortor, non malesuada mauris. Duis rutrum lectus vitae lobortis
下面的代码可以解决少于 255 个字符的文本。
有没有办法对超过 255 个字符的文本执行此操作?
Sub ModifyTextSingleV2()
Dim ws As Worksheet
Dim cell As Range
' Define worksheet
Set ws = Workbooks("workbook1").Sheets("Sheet1")
' The cell where the text is
Set cell = ws.Cells(1, 1)
' Delete 'lobortis' from the cell << doesn't work, but would work if were under 255 chars
cell.Characters(250, 8).Delete
End Sub
我想删除字符串中超过 255 个字符的部分,同时保持单元格中的格式相同。
这就是你正在尝试的吗?
Option Explicit
Sub ModifyTextSingleV2()
Dim ws As Worksheet
Dim cell As Range
Dim cellText As String
'~~> Change this to relevant worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
'~~> The cell where the text is
Set cell = ws.Cells(1, 1)
'~~> Get the cell value
cellText = cell.Value
'~~> Check if the text is more than 255 characters
If Len(cellText) > 255 Then
'~~> Keep only the first 255 characters
cellText = Left(cellText, 255)
'~~> Update the cell's value but preserve the character formatting
cell.Characters(256, Len(cell.Value) - 255).Delete
End If
End Sub
截图