使用InStr确定特定字符的出现次数?

时间:2016-12-13 20:32:52

标签: excel vba excel-vba

我正在做一些数据处理,我使用了代码

If InStr(1, cell.Value, "/") > 1 Then
    cell.Replace "/", ", "
End If

现在我的理解是,如果“/”出现不止一次,那么它将继续并用“,”替换它。然而,似乎即使只有1“/”它仍然执行替换。我不是编码向导,但似乎数学有点瑕疵。有谁知道可能是什么问题?

编辑:完整代码

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

2 个答案:

答案 0 :(得分:4)

如果你想替换所有" /"如果有两个以上,那么:

If (Len(myCell) - Len(Replace(myCell, "/", ""))) > 1 Then
    myCell = Replace(myCell.Text, "/", "")
End If

如果你想要别的东西,请具体说明。

答案 1 :(得分:0)

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数据过滤器一次性替换所有单元格而无需循环:

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