做你的后续问题 - 我可以更快地运行此宏吗? - 我在这里提交我的答案并投票将该问题作为副本结束。
如果我理解你,你想要获取H列中的所有值并从E列中删除它们?我会用一些阵列来加速它 -
Option Explicit
Sub DoTheThing()
Application.ScreenUpdating = False
Dim lastrow As Integer
'Find last row in column H to size our array
lastrow = ActiveSheet.Cells(Rows.Count, "H").End(xlUp).row
'Declare the array and then resize it to fit column H
Dim varkeep() As Variant
ReDim varkeep(lastrow - 1)
'Load column H into the array
Dim i As Integer
For i = 0 To lastrow - 1
varkeep(i) = Range("H" & i + 1)
Next
Dim member As Variant
'find last row in column E
lastrow = ActiveSheet.Cells(Rows.Count, "E").End(xlUp).row
'loop each cell in column E starting in row 2 ending in lastrow
For i = 2 To lastrow
'Make a new array
Dim myArray As Variant
'Load the cell into the array
myArray = Split(Cells(i, 5), " ")
Dim k As Integer
'for each member of this array
For k = LBound(myArray) To UBound(myArray)
member = myArray(k)
'call the contains function to check if the member exists in column H
If Contains(varkeep, member) Then
'if it does, set it to nothing
myArray(k) = vbNullString
End If
Next
'let's reprint the array to the cell before moving on to the next cell in column E
Cells(i, 5) = Trim(Join(myArray, " "))
Next
Application.ScreenUpdating = True
End Sub
Function Contains(arr As Variant, m As Variant) As Boolean
Dim tf As Boolean
'Start as false
tf = False
Dim j As Integer
'Search for the member in the keeparray
For j = LBound(arr) To UBound(arr)
If arr(j) = m Then
'if it's found, TRUE
tf = True
Exit For
End If
Next j
'Return the function as true or false for the if statement
Contains = tf
End Function
这将从列H中创建一个数组。然后它遍历E列中的每个单元格,将其解析为数组,针对保持数组搜索该数组的每个成员,如果找到,则删除该数组的成员。通过单元格后,它重新打印数组,找不到找到的数组。
数组通常比逐项更快,但另外,我们创建自己的函数而不是使用 慢 Find and Replace
方法。唯一的问题是数据中可能有额外的空格。如果是这样,我们可以快速查找并替换它。我发现更容易将数组的成员设置为空,而不是重新调整数组大小并移动元素。
为了完整起见,这里是一个从E列中删除多余空格的例程
Sub ConsecSpace()
Dim c As Range
Dim lastrow As Integer
lastrow = ActiveSheet.Cells(Rows.Count, "E").End(xlUp).Row
Dim strValue As String
For Each c In Range("E2:E" & lastrow)
strValue = c.Value
Do While InStr(1, strValue, " ")
strValue = Replace(strValue, " ", " ")
Loop
c = strValue
Next
End Sub