我是VBA的新手,我需要创建宏,它会在A列中找到包含“test”,“data”或“new”的所有单元格,并将所有这些单元格复制到B列,从B2开始,所有其他单元格应从C2开始复制到C列。
答案 0 :(得分:1)
了解您已经接受了答案,但如果要进行大量此类过滤,则迭代单元格可能会对性能产生负面影响。 尝试array
。还可以使用 LIKE
运算符来比较值,这是完美的wildcard operator
。将以下代码添加到VBA项目模块中。在工作表中添加一个按钮,并通过button click event
调用子例程。
Option Explicit
Sub filterSpecifics()
Dim rng As Range
Dim lastRow As Long
Dim vArray As Variant
Dim i As Integer
lastRow = Sheets(3).Cells(Rows.Count, "A").End(xlUp).Row
Set rng = Sheets(3).Range("A1").Resize(lastRow)
vArray = WorksheetFunction.Transpose(rng.Value)
For i = LBound(vArray) To UBound(vArray)
If Not IsEmpty(vArray(i)) Then
If Not vArray(i) Like "test*" And _
Not vArray(i) Like "data*" And Not vArray(i) Like "new*" Then
vArray(i) = "" '-- remove the value
End If
End If
Next i
'-- output the array to the column B
rng.Offset(0, 1).Resize(UBound(vArray)) = Application.Transpose(vArray)
End Sub
<强>输出:强>
答案 1 :(得分:0)
打开您的VBA编辑器并将下面的代码粘贴到Sheet1(在Microsoft Excel对象下):
Option Explicit
Sub MyMacro()
Dim iLastRow As Long
Dim i As Long
Dim sVal As String
iLastRow = range("A65536").End(xlUp).Row 'get last row in use
For i = 2 To iLastRow 'iterate trough rows from second to last in use
sVal = range("A" & i).Value
If sVal = "test" Or sVal = "data" Or sVal = "new" Then
range("B" & i).Value = sVal
Else
If sVal <> "" Then range("C" & i).Value = sVal
End If
Next i
End Sub
确保鼠标指针设置在过程MyMacro
内的某处,并按F5执行代码。它应该做你要求的魔术: - )