首页 > 解决方案 > 根据多个单元格的值设置范围变量

问题描述

我有这样的数据:(我不知道如何正确发布 excel 表,为此我使用了 apple-o-gize。我也真的希望这些不是真正的电子邮件)

     A               B
1  String     Email
2  Astring1   Aemail@nothingA.xom
3  Astring2   Aemail@nothingA.xom
4  Astring3   Aemail@nothingA.xom
5  Bstring1   Bemail@nothingB.xom
6  Bstring2   Bemail@nothingB.xom
7  Bstring3   Bemail@nothingB.xom
8  Bstring4   Bemail@nothingB.xom
9  Cstring1   Cemail@nothingC.xom
10 Cstring2   Cemail@nothingC.xom

我正在尝试根据电子邮件字段将范围设置为变量。

即对于“A”,下面的 myRng 将是 A2:A4,“B”将是 A5:A8,依此类推

Set myRng = Range("A1:A" & [the last row where the e-mails are the same])

我不认为 For...Next 或 Do 循环会起作用,或者至少,我不知道如何使它们起作用。

非常感谢任何帮助 - 谢谢!

标签: vbaexcel

解决方案


这是我所做的:

  1. 按电子邮件 IDS 对 A:B 列进行排序
  2. 在 C 列中,创建所有唯一电子邮件 ID 的列表。
  3. 确定每个电子邮件 ID 的计数。使用计数:

    =COUNTIF($B$2:$B$10,C2)
    
  4. 使用 match 确定电子邮件地址出现的第一个单元格

    =MATCH(C2,$B$2:$B$10,0)
    
  5. 创建地址范围

    =ADDRESS(E2,1,4)&":"&ADDRESS(E2+F2-1,1,4)
    
  6. 创建 G 列的命名范围。称它为“Range_List”

您的 Excel 文件将如下所示:

        A           B                       C               E          F           G
    1   String      Email               Unique Emails       count      Cell start  Range
    2   Astring1    Aemail@nothingA.xom Aemail@nothingA.xom 3          2           A2:A4
    3   Astring2    Aemail@nothingA.xom Bemail@nothingB.xom 4          5           A5:A8
    4   Astring3    Aemail@nothingA.xom Cemail@nothingC.xom 2          9           A9:A10
    5   Bstring1    Bemail@nothingB.xom
    6   Bstring2    Bemail@nothingB.xom
    7   Bstring3    Bemail@nothingB.xom
    8   Bstring4    Bemail@nothingB.xom
    9   Cstring1    Cemail@nothingC.xom
    10  Cstring2    Cemail@nothingC.xom

下一步 - VBA:

  1. 导入excel命名范围
  2. 使用 for 循环遍历命名范围
  3. 获取每个单元格的值并赋值给myRng
    示例:
    当i=1时,单元格的值为A2:A4
    i=2时,单元格的值为A5:A8
    以此类推。

Sub Ranges_Macro()

    Dim i As Integer
    Dim Range_List As Range
    Set Range_List = Sheet1.Range("Range_List")

    For i = 1 To Range_List.Count

        Dim myRng As Range
        Dim Range_String As String
        Range_List.Offset(i - 1, 0).Activate
        Range_String = ActiveCell.Value


        Set myRng = Range(Range_String)

    Next i

End Sub


推荐阅读