使用InStr来确定特定字符的出现次数?
我正在做一些数据处理,我使用的代码
If InStr(1, cell.Value, "/") > 1 Then cell.Replace "/", ", " End If
现在我的理解是,如果“/”不止一次出现,它会继续,并用“,”代替。 然而,好像即使只有1个“/”它仍然执行replace。 我不是编码向导,但是看起来这个math有一点缺陷。 有谁知道可能是什么问题?
编辑:完整的代码
Sub Title() Application.ScreenUpdating = False Dim rng As Range Dim ws As Worksheet Set ws = ActiveSheet Dim cell As Range Set rng = ws.Range(ws.Cells(2, 2), ws.Cells(ws.Rows.Count, 2).End(xlUp)) For Each cell In rng If InStr(1, cell.Value, " ") > 0 Then cell.Value = " " & cell.Value & " " End If Next cell rng.Replace " ", " " 'Data Breakdown 'Remove phrases rng.Replace "at *", "" rng.Replace "We're *", "" rng.Replace "We are *", "" rng.Replace "we're *", "" rng.Replace "we are *", "" For Each cell In rng If (Len(myCell) - Len(Replace(myCell, "/", ""))) > 1 Then myCell = Replace(myCell.Text, "/", "") End If If InStr(1, cell.Value, " Manager of ") > 0 Then cell.Replace " Manager of ", " Manager, " End If Next cell rng.Replace " IT ", " IT, " rng.Replace " Manager ", " Manager, " Application.ScreenUpdating = True End Sub
如果你想要replace所有的“/”,如果有两个以上,那么:
If (Len(myCell) - Len(Replace(myCell, "/", ""))) > 1 Then myCell = Replace(myCell.Text, "/", "") End If
如果你想要别的东西,请具体说明。
Like
运算符可以更容易地检查一个值是否包含或开始/结束的东西:
For Each cell In rng If cell Like "*/*/*" Then cell.Replace "/", ", " ' * matches 0 or more characters Next cell
另一个选项可以是拆分值并检查结果数组的上限:
For Each cell In rng a = Split(cell, "/") If UBound(a) > 1 Then cell.Value = Join(a, ", ") Next cell
您也可以使用Excel数据filter一次性replace所有单元格,而无需循环:
Set rng = Columns("F") ' the filter needs the first header cell rng.AutoFilter 1, "*/*/*" ' add Excel Data Filter to the Range rng.Replace "/", ", ", xlPart ' ignores the filtered cells rng.AutoFilter ' optional to remove the filter