根据另一个单元格中的文本replace部分string

5:00 AM 5:13 AM
上午6:10上午6:26
6:40 AM 6:56 AM
上午7:25上午7:41
8:15 AM 8:28 AM
9:10 AM 9:24 AM
10:10 AM 10:23 AM
11:10 AM 11:26 AM
12:02 PM 12:15 PM
12:50 PM 1:06 PM

我试图创build一个macros,我需要在当前单元格中replace单词AM或PM,而没有AM和PM时,如果上面的单元格有AM或PM

例如,第一行的时间保持不变,第二行的行显示时间如6:10和6:26,因为上面的单元格有AM。 PM行也是如此。 包含PM的第一行保持不变,但后面的行只显示数字。

我目前的代码是这样的,它似乎并没有工作..我的Excel文件只是崩溃,必须重新启动EXCEL 必需的结束表

'Remove additional AM and PM Dim i as Long, j as Long Dim celltxt as String For i= 2 To 200 j=3 Do While j<50 celltxt = Cells(i-1,j).Text If InStr( 1, celltext,("AM" Or "PM")) Then Cells(i,j).Replace What:="AM" Or "PM", Replacement:=" ", SearchOrder:=xlByColumns, MatchCase:=True Else End If Loop Next i End Sub 

我认为你需要尝试下面的代码:

 'Remove additional AM and PM Dim i as Long, j as Long Dim celltxt as String For i= 2 To 200 For j = 3 To 49 celltxt = Cells(i-1,j).Text If InStr( 1, celltext,("AM" Or "PM")) Then Cells(i,j).Replace What:="AM" Or "PM", Replacement:=" ", SearchOrder:=xlByColumns, MatchCase:=True Else End If Next j Next i End Sub 

希望这个帮助

1)你的代码崩溃,因为你不增加你的内部循环的计数器( j ),所以代码被困在一个无限循环(当你使用debugging器很容易弄清楚)

2)我认为replace不接受or – 相反,您必须发出2个单独的replace语句。

3)没有理由循环所有的数据。 您可以一次replace所有string(也许您必须调整范围的地址):

 Dim r As Range Set r = Range("C1:AW200") r.Replace What:="AM", Replacement:="", LookAt:=xlPart, MatchCase:=False r.Replace What:="PM", Replacement:="", LookAt:=xlPart, MatchCase:=False 

4)也许一个更好的解决scheme是从你的string创build真正的date,并正确地格式化。

我想我明白了

 'Remove additional AM and PM For m = 100 To 2 Step -1 For n = 3 To 30 celltxt = Cells(m - 1, n).Text If celltxt Like "*AM*" Then Cells(m, n).Replace What:="AM", Replacement:=" " Else End If Next n Next m For m = 100 To 2 Step -1 For n = 3 To 30 celltxt = Cells(m - 1, n).Text If celltxt Like "*PM*" Then Cells(m, n).Replace What:="PM", Replacement:=" " Else End If Next n Next m For m = 100 To 2 Step -1 For n = 3 To 30 celltxt = Cells(m - 1, n).Text If celltxt Like "*-*" Then Cells(m, n).Replace What:="PM", Replacement:=" " Else End If Next n Next m For m = 100 To 2 Step -1 For n = 3 To 30 celltxt = Cells(m - 1, n).Text If celltxt Like "*-*" Then Cells(m, n).Replace What:="AM", Replacement:=" " Else End If Next n Next m End Sub