在 VBA 中的电子表格对内循环
Posted
技术标签:
【中文标题】在 VBA 中的电子表格对内循环【英文标题】:Looping within spreadsheet pairs in VBA 【发布时间】:2022-01-09 22:52:01 【问题描述】:我在一个 Excel 文档中有 10 个不同的电子表格(a、b、c、d、e、f 等)。如何创建循环以比较特定的电子表格对(a vs d、b vs e、c vs f 等)?
Dim x As Integer
Dim y As Integer
Dim year1, year2 As Integer
Dim strname1, strname2, strname3, strname4 As String
Dim st
Dim p
strname1 = "Female"
strname2 = "Male"
strname3 = "Other"
strname4 = "Unknown"
year1 = 2019
year2 = 2020
For Each p In Array(2019, 2020)
For Each st In Array(strname1, strname2, strname3, strname4)
Worksheets("a").Activate
x = WorksheetFunction.SumIfs(Range("F9:F250"), Range("C9:C250"), p, Range("E9:E250"), st)
Worksheets("d").Activate
y = WorksheetFunction.SumIfs(Range("F7:F30"), Range("C7:C30"), p, Range("D7:D30"), st)
If x = y Then
MsgBox "Number of people correctly validated for" & " " & p & " " & st
Else
MsgBox "Error in validation for" & " " & p & " " & st
End If
Next st
Next p
【问题讨论】:
你是什么意思“特定的电子表格对”。您是否在某处定义了要比较的这些对(可能是二维数组甚至另一张表)?无论您将这些对存储在哪里(除了您的大脑)都是您想要循环的地方。喜欢..For Each pairRow in Sheets("myPairs").Range("A1:B10").Rows
(例如)。
感谢您的回复。我确实定义了这些对。例如,我想比较 a vs d、b vs e、c vs f 和 h vs g。我必须从 a、b、c 和 h 电子表格中选择完全相同的单元格范围,并从 d、e、f 和 g 中选择完全相同的单元格范围。
您对“电子表格”一词的使用令人困惑。听起来您的意思是 WORKSHEETS。
抱歉有任何混淆。我的意思是工作表
【参考方案1】:
在同一工作簿的新工作表(我们将其命名为 myPairs
)的 A 列和 B 列中输入您的配对,例如:
+---+---+
| A | B |
+---+---+
| a | e |
| b | f |
| c | g |
| d | h |
+---+---+
现在您可以在代码中引入循环:
Dim x As Integer
Dim y As Integer
Dim year1, year2 As Integer
Dim strname1, strname2, strname3, strname4 As String
Dim st
Dim p
strname1 = "Female"
strname2 = "Male"
strname3 = "Other"
strname4 = "Unknown"
year1 = 2019
year2 = 2020
For each pairRow in Sheets("myPairs").Range("A1:B4").Rows
firstSheetName = pairRow.Cells(1,1)
secondSheetName = pairRow.Cells(1,2)
For Each p In Array(2019, 2020)
For Each st In Array(strname1, strname2, strname3, strname4)
Worksheets(firstSheetName).Activate
x = WorksheetFunction.SumIfs(Range("F9:F250"), Range("C9:C250"), p, Range("E9:E250"), st)
Worksheets(secondSheetName).Activate
y = WorksheetFunction.SumIfs(Range("F7:F30"), Range("C7:C30"), p, Range("D7:D30"), st)
If x = y Then
MsgBox "Number of people correctly validated for" & " " & p & " " & st
Else
MsgBox "Error in validation for" & " " & p & " " & st
End If
Next st
Next p
【讨论】:
感谢您的解决方案。现在很好以上是关于在 VBA 中的电子表格对内循环的主要内容,如果未能解决你的问题,请参考以下文章