如何在变量的文本中搜索某些字符串?
在Excel VBA中,如果我想删除编号的文本myTextVariable = "ii. The man walks away"
,我可以
myTextVariable = Left(myTextVariable,Search(".",myTextVariable))
这会让我"The man walks away"
。
我怎么能在Word中这样做?我试过像myTextVariable = left(myTextVariable, Find.Text = ".")
这样的东西,但这不起作用。也试着像myTextVariable.Content.Find.Execute(findText:=".")
一样无济于事。
总体思路是我有一个包含许多条目的索引:
Automobile - type of car
Art Deco - an art type from back in the day
USA - a country
ii.Australia -a continent
iv. Greenland - another continent
Greenland - an icy continent
我正在循环浏览它们,并希望在文本之前删除任何i, ii, iii, iv, v, ..., x
,并且无法确定如何执行此操作。
感谢您的任何想法!
编辑:感谢@ScottCraner,我现在正在使用:
myTextVariable = myRange.Text
periodLoc = InStr(myTextVariable, ".")
If periodLoc < 10 And periodLoc > 0 Then
finalText = Trim(Mid(myTextVariable, InStr(myTextVariable, ".") + 1)) ' Trim(Right(myTextVariable, Len(myTextVariable) - periodLoc))
Else
finalText = myRange.Text
End If
但是现在有一个问题:有时文本将是"The U.S. - a country blah"
,这将删除“The U.”。如果是i, ii, ..., x
,我该如何搜索?我可以在InStr
使用RegEx吗?我当然可以用i, ii, iii, etc
做一个数组并循环遍历数组,但认为这可能不是最有效的方法。
感谢ScottCraner,我能够通过以下方式获得它:
Private Sub add_Selection_to_Index(ByVal myRange As Word.Range)
Dim textToPeriod$, finalText$
Dim periodLoc&
Debug.Print "Selection: " & myRange.Text
textToPeriod = myRange.Text
periodLoc = InStr(textToPeriod, "i.")
If periodLoc < 10 And periodLoc > 0 Then
finalText = Trim(Right(textToPeriod, Len(textToPeriod) - periodLoc - 1))
Else
periodLoc = InStr(textToPeriod, "v.")
If periodLoc < 10 And periodLoc > 0 Then
finalText = Trim(Right(textToPeriod, Len(textToPeriod) - periodLoc - 1)) ' Trim(Mid(textToPeriod, InStr(textToPeriod, "v.")))
Else
periodLoc = InStr(textToPeriod, "x.")
If periodLoc < 10 And periodLoc > 0 Then
finalText = Trim(Right(textToPeriod, Len(textToPeriod) - periodLoc - 1)) 'Trim(Mid(textToPeriod, InStr(textToPeriod, "x.")))
Else
finalText = myRange.Text
End If
End If
End If
ActiveDocument.Indexes.MarkEntry Range:=myRange, entry:=finalText, entryautotext:=finalText, crossreferenceautotext:="", _
bookmarkname:="", Bold:=False, Italic:=False, reading:=""
Debug.Print "Index: " & finalText
End Sub
答案 0 :(得分:2)
对@ScottCraner道歉,我很久以前曾使用function to convert roman numerals to arabic并认为上面的代码可能会利用该功能。 (感谢 mdmackkillop 在很久以前使用该功能。)请将该功能复制到您的模块中。
以下代码适用于任何罗马格式的数字(只要罗马数字少于10个字符 - 一个安全的赌注)
Option Explicit
Function StripNumeration(ByVal myRange As Range) As String
'--- assumes the myRange parameter value may contain leading roman
' numerals. Returns a string of the input text without the
' leading number
Dim periodLoc As Long
Dim numeration As String
Dim returnText As String
returnText = myRange.Text
periodLoc = InStr(1, returnText, ".", vbTextCompare)
If periodLoc < 10 And periodLoc > 0 Then
numeration = Left(returnText, periodLoc - 1)
If Arabic(numeration) <> "Fail" Then
returnText = Right(returnText, Len(returnText) - periodLoc)
End If
Else
End If
StripNumeration = Trim(returnText)
End Function