此函数遍历所有整数,只选择五个二进制值并将其写入电子表格。
运行此For x = 1 To 134217728
需要2.5天!!!!救命啊!
我怎样才能加快速度呢?
Function D2B(ByVal n As Long) As String
n = Abs(n)
D2B = ""
Do While n > 0
If n = (n \ 2) * 2 Then
D2B = "0" & D2B
Else
D2B = "1" & D2B
n = n - 1
End If
n = n / 2
Loop
End Function
Sub mixtures()
Dim x As Long
Dim y As Integer
Dim fill As String
Dim mask As String
Dim RowOffset As Integer
Dim t As Date
t = Now
fill = ""
For x = 1 To 134217728
mask = Right(fill & CStr(D2B(x)), Len(fill & CStr(D2B(x))))
Debug.Print mask
If x > 100000 Then Exit For
If Len(mask) - Len(WorksheetFunction.Substitute(mask, "1", "")) = 5 Then _
RowOffset = RowOffset + 1
For y = 1 To Len(mask)
If Len(mask) - Len(WorksheetFunction.Substitute(mask, "1", "")) = 5 Then _
Range("mix").Offset(RowOffset).Cells(y) = Mid(mask, y, 1)
Next
Next
Debug.Print DateDiff("s", Now, t)
End Sub
答案 0 :(得分:2)
首先猜测,我认为问题在于你按单元格进行单元格操作,这会导致许多读写访问。
你应该按范围进行,例如
vArr = Range("A1:C1000").Value
' it is array now, do something here effeciently
Range("A1:C1000").Value = vArr
答案 1 :(得分:1)
您希望查找所有28位数字,包含5个1位
有28 * 27 * 26 * 25 * 24/5/4/3/2 = 98280这样的数字
以下代码在我的电脑上花了大约10秒钟:
lineno = 1
For b1 = 0 To 27
For b2 = b1 + 1 To 27
For b3 = b2 + 1 To 27
For b4 = b3 + 1 To 27
For b5 = b4 + 1 To 27
Cells(lineno, 1) = 2 ^ b1 + 2 ^ b2 + 2 ^ b3 + 2 ^ b4 + 2 ^ b5
lineno = lineno + 1
Next
Next
Next
Next
Next
答案 2 :(得分:0)
mask = Right(fill & CStr(D2B(x)), Len(fill & CStr(D2B(x))))
上面的代码行做了两次相同的事情(CStr(D2B(x))
)
将CStr(D2B(x))
的结果存储在变量&在上面的代码行中使用该变量。
答案 3 :(得分:0)
我有两条建议:
像
这样的东西ws.Range(ws.cells(1, 1), ws.cells(UBound(dstArr, 1) + 1, UBound(dstArr, 2) + 1)) = dstArr
数组复制技巧大大提高了性能!