我正在过滤表格中的某些列:
ActiveSheet.Range("A1").AutoFilter Field:=3, Criteria1:="<>*/*"
我想要不包含/
然后我应用Selection.Replace
的目的是将该单元格的内容与/SUP
串联
Selection.Replace What:="???", Replacement:="???/SUP", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
但是它不起作用。我期望的输出是:
cellWith/ --- replace --- cellWith/
cellWithout --- replace --- cellWithout/SUP
有人可以帮助我吗?
答案 0 :(得分:1)
如果要使用AutoFilter
,则需要使用SpecialCells(xlCellTypeVisible)
,只需将"/SUP"
添加到单元格值的末尾即可。
Dim cel As Range
With ActiveSheet 'It's better to use the worksheet("Name") or a worksheet variable
'Filter
.Range("A1").AutoFilter Field:=3, Criteria1:="<>*/*"
'Loop through each visible cell in the range
For Each cel In .Range("C2", .Cells(.Rows.Count, "C").End(xlUp)).SpecialCells(xlCellTypeVisible)
'Concatenate the cells value and "/SUP"
cel.Value = Left(cel.Value, Len(cel.Value)) + "/SUP"
Next cel 'Loop
End With
添加_只是要彻底;如果要替换单元格中的最后三个字符并添加/SUP
,则可以更改此行...
cel.Value = Left(cel.Value, Len(cel.Value)) + "/SUP"
到...
cel.Value = Left(cel.Value, Len(cel.Value) - 3) + "/SUP"
答案 1 :(得分:1)
关于我的最后一条评论,使用变量数组循环,这应该很快,因为VBA会执行检查,而不是每次都引用单元格:
Sub test()
Dim lr As Long, i As Long, arr As Variant
lr = Cells(Rows.Count, 1).End(xlUp).Row
arr = Range(Cells(1, 1), Cells(lr, 1)).Value
For i = 2 To UBound(arr)
If InStr(arr(i, 1), "/") Then
Cells(i, 2).Value = arr(i, 1)
Else
Cells(i, 2).Value = arr(i, 1) & "/SUP"
End If
Next i
End Sub
我将值输出到b列(出于可视化目的,从循环的第二行开始),
答案 2 :(得分:0)
我不认为Range.Replace在这里适合您的预期用例。最好的选择是遍历数据并在必要时附加。这样的事情应该适合您:
Sub tgr()
Dim ws As Worksheet
Dim aData() As Variant
Dim i As Long
Set ws = ActiveWorkbook.ActiveSheet
With ws.Range("C2", ws.Cells(ws.Rows.Count, "C").End(xlUp))
If .Row < 2 Then Exit Sub 'No data
If .Cells.Count = 1 Then
ReDim aData(1 To 1, 1 To 1)
aData(1, 1) = .Value
Else
aData = .Value
End If
For i = LBound(aData, 1) To UBound(aData, 1)
If InStr(1, aData(i, 1), "/", vbBinaryCompare) = 0 Then aData(i, 1) = aData(i, 1) & "/SUP"
Next i
.Value = aData
End With
End Sub