VBA / Macro添加另一个具有条件的列

时间:2016-04-01 02:20:37

标签: excel vba filter macros keyword

我需要帮助在列M中编写名为“Person”的附加列或标题,条件为:

如果第一列(.divclass { height:200px; background-image: url("http://www.andypost.com/media/original/Andy- Post-Food-Photography-Waffle-with-Syrup.jpg"); } )包含这些关键字Column A,则"AU", "FJ", "NC", "NZ", "SG12"中的文字应为column M)

如果第一列(Person1)包含这些关键字Column A"ID", "PH26", "PH24", "TH", "ZA",)中的文字应为column M

如果第一列(Person2)包含这些关键字Column A,则("JP", "MY", "PH", "SG", "VN")中的文字应为column M

我想让这个动作成为最后一件事(在所有事情之后)。

我尝试录制宏。过滤关键字,然后手动输入,然后向下滑动复制,但似乎应该有另一种方法粘贴过滤后的数据。

范围也应该是动态的,因为每次我都会有不同的数据量

到目前为止,我的代码如下:

Person3

2 个答案:

答案 0 :(得分:1)

尝试以下代码

Sub testing()
    last = Range("A" & Rows.Count).End(xlUp).Row
    For i = 1 To last
        If Cells(i, 1) = """AU"", ""FJ"", ""NC"", ""NZ"", ""SG12""," Then
            Cells(i, 13) = "Person1"
        ElseIf Cells(i, 1) = """ID"", ""PH26"", ""PH24"", ""TH"", ""ZA"","  Then
            Cells(i, 13) = "Person2"
        ElseIf Cells(i, 1) = """JP"", ""MY"", ""PH"", ""SG"", ""VN""," Then
            Cells(i, 13) = "Person3"
        [..]
        End If
    Next i
End Sub

答案 1 :(得分:1)

使用OR的嵌套IF公式可以实现此目的。

With Worksheets("Sheet1")   '<~~ you should know what worksheet you are on!
    With Range(.Cells(2, 1), .Cells(Rows.Count, 1).End(xlUp))
        .Offset(0, 12).FormulaR1C1 = _
            "=if(or(rc1={""AU"", ""FJ"", ""NC"", ""NZ"", ""SG12""}), ""Person1"", " & _
             "if(or(rc1={""ID"", ""PH26"", ""PH24"", ""TH"", ""ZA""}), ""Person2"", " & _
             "if(or(rc1={""JP"", ""MY"", ""PH"", ""SG"", ""VN""}), ""Person3"", " & _
             "TEXT(,))))"
        'optionally revert the formulas to values
        '.Offset(0, 12) = .Offset(0, 12).value
    End With
End With