VBA - 根据条件改变细胞的值

时间:2016-10-14 11:53:00

标签: excel vba replace cell contains

似乎是一个简单的问题,但我无法在这里找到答案。去年我已经使用了StackOverflow,并最终决定自己提问,我确定有人知道答案!

情况: 我有一列具有唯一文件名的值,如果它们是否已处理。例如:" 20160810_123_a.xml已处理"或" 20160810_123_b.xml失败"文件名的长度会发生变化,因此它不是静态的。我在不同的报告中使用这些值,并且只想要处理'已处理'或者'失败'取决于原始内容中的内容。

我猜我需要某种If循环,它会做类似这样的事情: 在范围I:I中,如果单元格的值包含"已处理",则用" Processed"替换整个单元格。如果单元格的值包含"失败",则用"失败替换整个单元格。

提前致谢!

2 个答案:

答案 0 :(得分:3)

试试这个

Sub main()
    With Worksheets("Conditions") '<--| change "Conditions" to your actual data sheet
        With .Range("I1", .Cells(.Rows.Count, "I").End(xlUp)).SpecialCells(XlCellType.xlCellTypeConstants) '<--| change "I"s to your actual column index where to search for processed/failed
            .Replace what:="*processed*", replacement:="Processed", LookAt:=xlWhole, MatchCase:=False
            .Replace what:="*failed*", replacement:="Failed", LookAt:=xlWhole, MatchCase:=False
        End With
    End With
End Sub

答案 1 :(得分:0)

这对我有用:

Option Explicit

Sub Test()

Dim arr() As Variant
Dim i As Long
Dim myRange As Range
Dim wf As WorksheetFunction

Set wf = Application.WorksheetFunction
With ActiveSheet
    Set myRange = .Range(.Cells(1, 1), Cells(.Rows.Count, 1).End(xlUp))
End With

arr = myRange
For i = 1 To UBound(arr)
    arr(i, 1) = wf.Proper(Right(arr(i, 1), Len(arr(i, 1)) - wf.Find(" ", arr(i, 1))))
Next i
myRange.Offset(0, 1) = arr

End Sub