我是VBA的普通用户,因此无法解决问题,请帮助我。
我必须在excel电子表格中的单元格中的句子中找到斜体字:
快速的棕色狐狸跳上了一只懒狗。
我想要这个:
The <italics>quick</italics> brown <italics>fox</italics> jumped upon a lazy dog.
非常感谢您的帮助!
使用Characters
Object,您可以检查文本中每个字符的Characters.Font.Italic
。这是一个完整的例子:
Option Explicit
Const ITALIC_TAG_OPENING As String = "<italics>"
Const ITALIC_TAG_CLOSING As String = "</italics>"
Public Sub AddItalicTags(targetCell As Range)
Dim finalText As String: finalText = targetCell.Value
Dim c As Characters
Dim lastCharItalic As Boolean
Dim i As Integer, addedLength As Integer, pos As Integer
For i = 1 To Len(targetCell.Text)
pos = i + addedLength
Set c = targetCell.Characters(i, 1)
If c.Font.Italic Then
If Not lastCharItalic Then
lastCharItalic = True
finalText = InsertText(finalText, pos, ITALIC_TAG_OPENING)
addedLength = addedLength + Len(ITALIC_TAG_OPENING)
End If
Else
If lastCharItalic Then
lastCharItalic = False
finalText = InsertText(finalText, pos, ITALIC_TAG_CLOSING)
addedLength = addedLength + Len(ITALIC_TAG_CLOSING)
End If
End If
Next
If lastCharItalic Then finalText = finalText & ITALIC_TAG_CLOSING
targetCell.Value = finalText
End Sub
Public Function InsertText(ByVal originalText As String, _
ByVal pos As Integer, _
ByVal textToAppend) As String
InsertText = Left$(originalText, pos - 1) & _
textToAppend & _
Mid$(originalText, pos, Len(originalText) - (pos - 1))
End Function
用法:
AddItalicTags Sheet1.Range("A1")
输出:
The <italics>quick</italics> brown <italics>fox</italics> jumped upon a lazy dog.
注意:如果您的单元格中有其他格式(例如,粗体,颜色等),它将会丢失,因此您可能需要调整上述方法以将其考虑在内。
我从我在评论中提到的post中获取了代码并“减少”了它。我从艾哈迈德那里拿走了CONSTANTS,你走了
Public Function getHTMLFormattedString(r As Range) As String
Const ITALIC_TAG_OPENING As String = "<italics>"
Const ITALIC_TAG_CLOSING As String = "</italics>"
Dim isItalic As Boolean
Dim s As String
Dim cCount As Long
Dim i As Long
Dim c As Characters
isItalic = False
s = ""
cCount = 0
On Error Resume Next
cCount = r.Characters.Count
On Error GoTo 0
If cCount > 0 Then
For i = 1 To cCount
Set c = r.Characters(i, 1)
If isItalic And Not c.Font.Italic Then
isItalic = False
s = s & ITALIC_TAG_CLOSING
End If
If c.Font.Italic And Not isItalic Then
isItalic = True
s = s + ITALIC_TAG_OPENING
End If
s = s & c.Text
If i = cCount Then
If isItalic Then s = s & ITALIC_TAG_OPENING
End If
Next i
Else
s = r.Text
If r.Font.Italic Then s = ITALIC_TAG_OPENING & s & ITALIC_TAG_CLOSING
End If
getHTMLFormattedString = s
End Function