根据条件创建新的单元格值

时间:2018-05-25 16:36:55

标签: vba excel-vba excel

我需要有关VBA代码的帮助,该代码将在我的数据集的新列中设置条件。

基本上,如果单元格AB2包含“iMac”或“MacBook”,则在单元格AD2中分别写入“iMac”或“MacBook”。然后对整个数据集执行此操作。注意:AB栏是项目描述的列表,其中我只对iMac和MacBook感兴趣。

Dim celltxt As String
Dim lastRow As Long
lastRow = Range("A" & Rows.Count).End(xlUp).Row

celltxt = ActiveSheet.Range("AB2").Text
If InStr(1, celltxt, "iMac") Then
    Range("AD2").Select
    Selection.Value = "iMac"
ElseIf InStr(1, celltxt, "MacBook") Then
    Range("AD2").Select
    Selection.Value = "MacBook"
End If
Range("AD2").AutoFill Destination:=Range("AD2:AD" & lastRow)

我觉得你不能自动填写if-else ......

如果有更好的方法来解决这个问题,我愿意接受建议。

3 个答案:

答案 0 :(得分:2)

我想你想要一个功能。加上这个:

Function FindModel(Expr As String) As String
    For Each Model In Array("iMac", "MacBook")
        If InStr(1, Expr, Model, vbTextCompare) Then
            FindModel = Model
            Exit Function
        End If
    Next
End Function

然后在表单中使用它:=FindModel(AB2)

答案 1 :(得分:1)

对于踢腿和咯咯笑声......

=IF(NOT(ISERROR(FIND("iMac",AB2))),"iMac",IF(NOT(ISERROR(FIND("MacBook",AB2))),"MacBook","Not sure what product, but not an iMac or MacBook"))

答案 2 :(得分:0)

您可以使用AutoFilter

With ActiveSheet
    With .range("AB1:AB" & .Cells(.Rows.Count, 1).End(xlUp).row)
        .AutoFilter field:=1, Criteria1:="iMac", Operator:=xlOr, Criteria2:="MacBook"
        With .Resize(.Rows.Count - 1).Offset(1)
            If CBool(Application.Subtotal(103, .Cells)) Then .SpecialCells(xlCellTypeVisible).Offset(, 2).FormulaR1C1 = "=RC[-2]"
        End With
    End With
    .AutoFilterMode = False
End With