[英]Replace part of a string based on text in another cell
5:00 AM 5:13 AM
上午6:10上午6:26
上午6:40上午6:56
上午7:25上午7:41
上午8:15上午8:28
9:10 AM 9:24 AM
上午10:10上午10:23
11:10 AM 11:26 AM
下午12:02下午12:15
12:50 PM 1:06 PM
我正在尝试创建一个宏,如果上面的单元格具有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
),因此代码陷入了一个无限循环中(使用调试器时很容易弄清楚)
2)我认为替换不接受or
条款。 相反,您必须发出2条单独的replace语句。
3)没有理由遍历所有数据。 您可以一次替换所有字符串(也许您必须调整范围的地址):
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)也许更好的解决方案是从字符串中创建实际日期并正确设置其格式。
我想我明白了
'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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.