Select 范围内的大小写

Select Case on a range

我基本上有多个要分类的变量。我有一个变量属于哪个类别的列表,但是鉴于我有 40,000 个条目,手动执行它是及时的。

基本上我的数据是这样的:a、b、c 在 A 组中,d、e、f 在 B 组中,依此类推。 我试图使用 Select 案例,但我不知道如何在范围内 运行 它;意思是,我在 A 列中有变量。我希望它检查 A 列中的每个单元格,并假设它的 d 然后在 B 列中写入 "Group B"。 这就是我作为初学者所能做到的

 Case "a", "b", "c"
 cells(1,2).Value = "Group A"
 Case Else
 cells(1,2).Value = "Not Defined"
 End Select
 End Sub

你需要一个循环:

    Dim r As Long
    For r = 1 To Cells(Rows.Count, "A").End(xlUp).Row
        Select Case Cells(r, "A").Value
            Case "a", "b", "c"
                Cells(r, 2).Value = "Group A"
            Case "d", "e", "f"
                Cells(r, 2).Value = "Group B"
            Case Else
                Cells(r, 2).Value = "Not Defined"
        End Select
    Next
End Sub

您可以 运行 更快地 VBA 相当于

,而不是逐个单元地循环

=IF(OR(A2={"a","b","c"}),"Group A",IF(OR(A2={"d","e","f"}),"Group B","not me"))

Value部分与复制粘贴特殊值相同,即删除公式

Dim rng1 As Range
With ActiveSheet
    Set rng1 = .Range(.[a1], .Cells(.Rows.Count, "a").End(xlUp))
    rng1.Offset(0, 1).FormulaR1C1 = "=IF(OR(RC[-1]={""a"",""b"",""c""}),""Group A"",IF(OR(RC[-1]={""d"",""e"",""f""}),""Group B"",""not me""))"
    rng1.Offset(0, 1).Value = rng1.Offset(0, 1).FormulaR1C1
End With