操作没有循环的数组 [英] Manipulating arrays without loops
本文介绍了操作没有循环的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
学习VBA for Excel,我试图在不使用循环的情况下进行尽可能多的编码.作为练习,我将两个相邻范围的数量相乘,得出了这样的结果:
Learning VBA for Excel, I am trying to do as much of my coding without the use of loops. As an exercise, multiplying the numbers of two adjacent ranges, I came up with this:
Sub multiply_range()
Dim a, b, c As Range
Set a = Range("a1:a5")
Set b = Range("b1:b5")
Set c = Range("c1:c5")
a.Value = Evaluate("row(" & a.Address & ")")
b.Value = Evaluate("row(" & b.Address & ")")
c.Value = Evaluate(a.Address & "*" & b.Address)
End Sub
哪个效果很好.现在,我想做类似的事情,但改用数组.从以下代码开始:
Which works quite nicely. Now I want to do something similar but using arrays instead. Starting with this code:
Sub multiply_array()
Dim aArr(), bArr(), cArr()
ReDim aArr(5), bArr(5), cArr(5)
For i = 0 To 4
aArr(i) = i + 1
bArr(i) = i + 1
Next
For i = 0 To 4
cArr(i) = aArr(i) * bArr(i)
Next
For i = 0 To 4
Range("D" & i + 1).Value = cArr(i)
Next
End Sub
如何用不使用循环的代码替换这些FOR循环中的任何一个?
How would you replace any one of these FOR loops with code that doesn't use loops?
推荐答案
在这里:
Sub Squares()
Dim n&
n = 5
[d1].Resize(n) = Evaluate("row(1:" & n & ")^2")
End Sub
更新
这是不使用循环且不使用范围的变体:
Here is a variant that uses no loops and no ranges:
Sub Squares()
Dim a, b, n&
n = 5
a = Array(1, 2, 3, 4, 5)
b = Array(1, 2, 3, 4, 5)
[d1].Resize(n) = Evaluate("{" & Join(a, ";") & "}*{" & Join(b, ";") & "}")
End Sub
这篇关于操作没有循环的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文