有没有办法将它压缩成一个循环,而不是进行多次迭代?
Posted
技术标签:
【中文标题】有没有办法将它压缩成一个循环,而不是进行多次迭代?【英文标题】:Is there any way to condense this into a single loop, as opposed to doing several iterations? 【发布时间】:2021-12-14 01:33:35 【问题描述】:提前感谢您的帮助。
基本上我要做的是从 Sheet1.Cells(2, 3) 中的第一个字符开始的字符串中的每 66 个字符(总共是 20 次,字符串长度总共是 1,320 个字符)。一旦我得到第 66 个字符的 20 次出现,我想在 Sheet2.Cells(i, 2) 上打印这 20 个实例,其中 i = 2 到 21。最后,我想循环到 Sheet1.Cells 的下一个字符串(3, 3),做同样的计算,在 Sheet2.Cells(i + 20, 2) 中打印结果,其中仍然是 i = 2 到 21。
下面是我拥有的代码,它确实有效。问题是我将不得不重复这些代码块一千多次。有什么方法可以压缩它,所以它会计算每一行,直到它到达 Sheet1.Cells(2, 100)?附加的截图链接描述了我正在尝试完成的事情。 https://imgur.com/a/aBrlAzd
Sub Decode_String()
Dim Fault_Block(2000)
For i = 2 To 21
For j = 1 To 20
Fault_Block(i) = Mid(Sheet1.Cells(2, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 1, 2) = Fault_Block(i)
Next
Next
For i = 22 To 41
For j = 1 To 20
Fault_Block(i) = Mid(Sheet1.Cells(3, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 21, 2) = Fault_Block(i)
Next
Next
For i = 42 To 61
For j = 1 To 20
Fault_Block(i) = Mid(Sheet1.Cells(4, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 41, 2) = Fault_Block(i)
Next
Next
End Sub
【问题讨论】:
【参考方案1】:您在正确的轨道上,您只需要围绕您的逻辑添加一个循环以在 Sheet1 单元格中移动
Sub Decode_String()
Dim Fault_Block(2000)
Dim counter
' loop through cells
For c = 2 To 100
For j = 1 To 20
counter = counter + 1
Fault_Block(counter) = Mid(Sheet1.Cells(c, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + ((c - 2) * 20) + 1, 2) = Fault_Block(counter)
Next
Next
End Sub
如果出于其他原因不需要 Fault_Block 数组,可以将其简化为:
Sub Decode_String()
' loop through cells
For c = 2 To 100
For j = 1 To 20
Sheet2.Cells(j + ((c - 2) * 20) + 1, 2) = Mid(Sheet1.Cells(c, 3), (66 * j) - 65, 4)
Next
Next
End Sub
【讨论】:
【参考方案2】:以下是浓缩的循环:
Sub Decode_String()
For i = 2 To 21
For j = 1 To 20
Sheet2.Cells(j + 1, 2) = Mid(Sheet1.Cells(2, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 21, 2) = Mid(Sheet1.Cells(3, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 41, 2) = Mid(Sheet1.Cells(4, 3), (66 * j) - 65, 4)
Next
Next
End Sub
如果你想让它一直循环到第 100 行,试试这个:
Sub Decode_String()
For i = 2 To 21
For j = 1 To 100
Sheet2.Cells(j + 1, 2) = Mid(Sheet1.Cells(2, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 21, 2) = Mid(Sheet1.Cells(3, 3), (66 * j) - 65, 4)
Sheet2.Cells(j + 41, 2) = Mid(Sheet1.Cells(4, 3), (66 * j) - 65, 4)
Next
Next
End Sub
【讨论】:
以上是关于有没有办法将它压缩成一个循环,而不是进行多次迭代?的主要内容,如果未能解决你的问题,请参考以下文章