我有一个宏来搜索一个单词(“一月”),并将其旁边的空间转换为受保护的空间。我也想搜索一年中的其他月份。有没有一种方法可以在同一函数中搜索其他月份,而不是复制和粘贴我的代码11次,而每次都搜索不同的月份?到目前为止,这是我的代码。如果可能的话,我只对更改搜索文本行感兴趣,因为其余的工作都很好,而我在VBA方面也不那么擅长,基本上其他任何事情很快都会变得令人困惑,大声笑。
[我有另一个搜索功能,可以执行相同的操作,但是可以跟在任何数字(“([[0-9])”)后面并且可以正常工作,我只想将12个潜在的搜索功能缩短为一个。
Dim sFindText As String
sFindText = "January "
Selection.Find.Execute sFindText
Do Until Selection.Find.Found = False
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.TypeBackspace
Selection.TypeText Text:=" "
Selection.Find.Execute
Loop
End Sub
是,创建一个月数组,然后逐月遍历该数组。简单地:
Dim arrMonths() As Variant
Dim i As Long
arrMonths = Array("Jan", "Feb", ..., "Dec")
For i = LBound(arrMonths) To UBound(arrMonths)
sFindText = arrMonths(i)
Selection.Find.Execute sFindText
Do Until Selection.Find.Found = False
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.TypeBackspace
Selection.TypeText Text:=" "
Selection.Find.Execute
Loop
Next i
对于每个人来说,听起来都是不错的前进。这是一个示例,说明了如何将您的代码(未经测试的)放入一年中几个月的数组中的For Each块中。
Dim item As Variant
Dim months(1 To 2) as String
Dim str As String
months(1) = "January ": months(2) = "February "
For Each item In months
Selection.Find.Execute item
Do Until Selection.Find.Found = False
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.TypeBackspace
Selection.TypeText Text:=" "
Selection.Find.Execute
Loop
Next