1

我使用的宏的新版本(使其更快)在新的(原始)工作簿中运行,但在

我的“工作”工作簿(有其他宏)只有在我运行宏时才会运行新original

ona 字段然后在它之后运行新宏,然后它适用于任何字段。

或者,如果我关闭然后打开 WB 然后运行新宏,则新宏在“工作”工作簿中工作。

这是唯一以这种方式运行的宏。

有人可以看到这是新宏的问题,还是我的“工作”工作簿中存在隐藏问题或冲突

谢谢

Sub RemoveCharList()
fRemoveCharList Array("field2", "field4", "field5", "field7"), Array("]", "&", "%")
End Sub

新宏

Sub fRemoveCharList(ColArray As Variant, char As Variant)
Dim j As Long, Heading As Variant, headingFound As Range
For Each Heading In ColArray
Set headingFound = Range("1:1").Find(What:=Heading)
If Not headingFound Is Nothing Then
    With Range(headingFound, Cells(Rows.Count, headingFound.Column).End(xlUp))
        For j = LBound(char) To UBound(char)
            .Replace char(j), vbNullString
         Next
      End With
    End If
  Next
End Sub

原始宏

Sub fRemoveCharList(ColArray As Variant, char As Variant)

Dim x As Variant
Dim LR As Long, i As Long, j As Long
Dim Heading As Variant
Dim headingFound As Range
Dim lngColIndex As Long

For Each Heading In ColArray
    On Error Resume Next
    Set headingFound = Range("1:1").Find(What:=Heading, LookIn:=xlFormulas, LookAt:=xlPart)
    Err.Clear: On Error GoTo 0: On Error GoTo -1
    If Not headingFound Is Nothing Then lngColIndex = headingFound.Column
    'If headingFound.Column Then lngColIndex = headingFound.Column


  LR = Cells(Rows.Count, lngColIndex).End(xlUp).Row

  For i = 1 To LR
      With Cells(i, lngColIndex)
          x = .Value
          For j = LBound(char) To UBound(char)
              x = Replace(x, char(j), vbNullString)
          Next
          .Value = x
       End With
    Next i
  Next
End Sub
4

1 回答 1

1

告诉 Range 它属于哪个工作表总是一个好主意,否则它将占用 ActiveSheet 范围。

不需要for loop( For i = 1 To LR) 遍历每个单元格并检查特殊字符,而是代码可以在整个范围内搜索特殊字符(第一个单元格到底部)并使用替换方法。

我希望这些更改能让代码运行得更快。

Sub fRemoveCharList(ColArray As Variant, char As Variant)


    Dim LR As Long, j As Long
    Dim Heading As Variant
    Dim headingFound As Range, rng As Range


    With ThisWorkbook.Sheets("Sheet1")
        For Each Heading In ColArray
            Set headingFound = .Rows("1:1").Find(What:=Heading, LookIn:=xlFormulas, LookAt:=xlPart)

            If Not headingFound Is Nothing Then

                LR = .Cells(.Rows.Count, headingFound.Column).End(xlUp).Row
                Set rng = .Range(headingFound, .Cells(LR, headingFound.Column))

                For j = LBound(char) To UBound(char)
                    rng.Replace char(j), vbNullString
                Next

            End If
        Next
    End With
End Sub
于 2013-10-02T01:47:06.183 回答