如果我理解正确,您想对具有特定字符“[”和“]”的任何单元格执行某些操作。你想对那种单元格做什么,你想删除所有那些“[”、“]”以及这两个特定字符之间的值。
活动工作表中的示例数据:
带有黄色数据的单元格分散在活动工作表中的任何单元格中。
如果您的数据与上图相似,并且下图是您运行子程序后的预期结果:
那么子是这样的:
Sub test()
Dim c As Range
Dim pos1 As Long: Dim pos2 As Long
Do
Set c = ActiveSheet.UsedRange.Find("[", LookAt:=xlPart)
If Not c Is Nothing Then
Do
pos1 = InStr(c.Value, "["): If pos1 = 0 Then Exit Do
pos2 = InStr(c.Value, "]")
c.Replace What:=Mid(c.Value, pos1, pos2 - pos1 + 1), Replacement:="", LookAt:=xlPart
Loop
End If
Loop Until c Is Nothing
End Sub
sub中有两个循环。
Loop-A 是查找活动工作表中任何具有“[”字符的单元格并将其作为 c 变量
当没有找到具有“[”字符的单元格时,此循环 A 将停止。
Loop-B 是在找到的单元格中有“[”时执行某些操作。
如果在找到的单元格中不再有“[”字符,则此循环 B 将停止。
sub 在这个循环-B 中所做的就是找到“[”的位置作为 pos1 变量,并找到“]”的位置作为 pos2 变量。然后它替换“[”,“]”
以及在找到的单元格(c 变量)值中的这两个字符之间的任何文本,没有任何内容(“”)。
看到示例数据后,我认为最好在 MS Words 应用程序中进行。所以我在互联网上搜索如何在 MS Words 应用程序中进行 VBA。不完全确定它是否是正确的语法,但似乎下面的代码(MS Word VBA 模块)按预期工作。
Sub test()
Dim pos1 As Long: Dim pos2 As Long
Dim txt As String: Dim slice As String: Dim rpl As String
Do
pos1 = InStr(ActiveDocument.Content, "[")
If pos1 = 0 Then Exit Do
pos2 = InStr(ActiveDocument.Content, "]")
txt = Mid(ActiveDocument.Content, pos1, pos2 - pos1 + 1)
If Len(txt) > 250 Then
slice = Left(txt, 250): rpl = "["
Else
slice = txt: rpl = ""
End If
With ActiveDocument.Content.Find
.Execute FindText:=slice, ReplaceWith:=rpl, _
Format:=True, Replace:=wdReplaceAll
End With
Loop
End Sub
sub 的过程与 Excel 应用程序中的过程类似。不同之处在于,此子检查要删除的文本(txt 变量)中的字符是否超过 250,然后它将前 250 个字符切片为切片变量,并将“[”作为替换为 rpl 变量。
如果 txt 变量不超过 250 个字符,那么 slice 变量值与 txt 变量值相同,而 rpl 变量值则直接无 ---> ""。
警告:
在我的电脑里,该子需要将近 2 分钟才能完成 MS Words 应用程序中的工作数据来自 Excel 工作表示例数据的 A 列。