vba - 根据多个单元格的值设置范围变量
问题描述
我有这样的数据:(我不知道如何正确发布 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 循环会起作用,或者至少,我不知道如何使它们起作用。
非常感谢任何帮助 - 谢谢!
解决方案
这是我所做的:
- 按电子邮件 IDS 对 A:B 列进行排序
- 在 C 列中,创建所有唯一电子邮件 ID 的列表。
确定每个电子邮件 ID 的计数。使用计数:
=COUNTIF($B$2:$B$10,C2)
使用 match 确定电子邮件地址出现的第一个单元格
=MATCH(C2,$B$2:$B$10,0)
创建地址范围
=ADDRESS(E2,1,4)&":"&ADDRESS(E2+F2-1,1,4)
- 创建 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:
- 导入excel命名范围
- 使用 for 循环遍历命名范围
- 获取每个单元格的值并赋值给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
推荐阅读
- python - 如何使用while循环从字符串中检索唯一字符
- python - 从 Mac 上的 JuPyter 笔记本向 R 脚本传递参数,反之亦然?
- python - 在没有循环的数组矢量化(1D)期间索引 numpy 数组中的其他值
- javascript - 使用 document.querySelector('#id') 和 document.getElementById('id') 的区别
- linker - 每个引用是否都有符号条目
- c - 如何在初始化时发送 HTTPS 请求
- c# - int 的数组返回对象引用未设置为对象的实例
- python-3.x - 强制线性回归模型通过特定点
- javascript - create-react-app 自版本 4.0.1 起不起作用如何删除旧版本并安装它的新版本
- python - Python:FileNotFoundError:[Errno 2] 没有这样的文件或目录:'C:\\Users\\Aditya Bhatt\\Desktop\\Aditya\\SampleData.csv'