excel - VBA - 从多个工作表和范围创建字典
问题描述
我正在从多个工作表和范围创建字典。我的代码正在运行,但看起来非常不愉快。在我的知识中应该缺少一些基本的东西,这并不奇怪,因为这是我在 VBA 中的第一个项目。如何在一个循环中实现这一点?非常感谢任何帮助。
' Get the range of all the adjacent data using CurrentRegion
Dim rg1 As Range, rg2 As Range, rg3 As Range, rg4 As Range, rg5 As Range, rg6 As Range, rg7 As Range
Set rg1 = sheet1.Range("A1").CurrentRegion
Set rg2 = sheet2.Range("A1").CurrentRegion
Set rg3 = sheet3.Range("A1").CurrentRegion
Set rg4 = sheet4.Range("A1").CurrentRegion
Set rg5 = sheet5.Range("A1").CurrentRegion
Set rg6 = sheet6.Range("A1").CurrentRegion
Set rg7 = sheet7.Range("A1").CurrentRegion
Dim oID As clsItem, i As Long, j As Long, Id As Long
'read through the data
For i = 3 To rg1.rows.count
Id = rg1.Cells(i, 1).value
' Create a new clsDetector object
Set oID = New clsItem
' Add the new clsDetector object to the dictionary
dictName.add Id, oID
' Set the values
oID.ItemName = rg1.Cells(i, 70).value
Next i
'
'
'Same loops for rg2, rg3, rg4, rh5, rg6 and rg7
'
'
解决方案
由于工作表从 1 到 7,您可以像这样循环遍历它们。
Sub LoadRangesIntoDict()
Dim i As Integer
Dim s As Integer
Dim ws As Worksheet
Dim rng As Range
Dim oID As clsItem, i As Long, j As Long, Id As Long
' Loop through each sheet
For s = 1 To 7
Set ws = Sheets("Sheet" & s)
Set rng = ws.Range("A1").CurrentRegion
'read through the data
For i = 3 To rng.Rows.Count
Id = rng.Cells(i, 1).Value
' Create a new clsDetector object
Set oID = New clsItem
' Add the new clsDetector object to the dictionary
dictName.Add Id, oID
' Set the values
oID.ItemName = rng.Cells(i, 70).Value
Next i
Next s
End Sub
推荐阅读
- google-coral - 如何在开发板上使用加密处理器?
- debugging - 在 Google Apps 脚本中,使用新的 V8 运行时时断点的工作方式是否有所不同?
- swift - Swift:核心数据模型关系到镜像 API 视图模型
- wso2 - WSO2 IS Analytics 的用户管理
- ajax - 我可以把分页()放在哪里?
- scala - 如何使用 Databricks Job Spark 配置 spark_conf?
- python - 在 Python 中从年份中减去月份
- java - 使用 MouseClicked 获取光标坐标时出现此错误。“对于 MouseEvent 类型,方法 getX() & getY() 未定义”
- postgresql - 在另一个表的日期列上进行日期驱动的表分区
- node.js - 在 Node.js 的终端中删除重复的空行