【问题标题】:VBA/Macro to add another colum with conditionsVBA/宏添加另一列有条件
【发布时间】:2016-07-20 16:59:05
【问题描述】:

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

如果第一列(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

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

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

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

以下是我目前的代码:

Sub person()

    Selection.AutoFilter
    ActiveSheet.Range("$A$1:$L$38").AutoFilter Field:=1, Criteria1:=Array("AU", _
        "FJ", "NC", "NZ", "SG12"), Operator:=xlFilterValues
    ActiveWindow.LargeScroll ToRight:=1
    Range("M2").Select
    ActiveCell.FormulaR1C1 = "Person1"
    Selection.FillDown
End Sub

【问题讨论】:

    标签: excel vba filter macros keyword


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      带有 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-25
        • 1970-01-01
        • 2019-12-22
        • 1970-01-01
        • 1970-01-01
        • 2011-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多