修改后的宏行为奇怪,既有工作又无法工作

时间:2013-10-01 22:16:54

标签: excel-vba vba excel

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

我的“工作”工作簿(包含其他宏)新宏只有在我运行original

时才会运行

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

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

这是唯一一种行为方式的宏。

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

由于

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

1 个答案:

答案 0 :(得分:1)

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

不需要for loop(对于i = 1到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