gpt4 book ai didi

循环内的 VBA 偏移 - 需要永远运行

转载 作者:行者123 更新时间:2023-12-03 00:07:34 26 4
gpt4 key购买 nike

我是编程新手,我认为 VBA 是一个很好的起点,因为我在 Excel 中做了很多工作。

我创建了一个宏,它从输入框中获取一个整数(我一直使用 2、3 和 4 来测试),并创建该数字的一组 4 层层次结构;例如输入“2”会产生

1.0.0.0
1.0.0.1
1.0.0.2
1.0.1.0
1.0.1.1
1.0.1.2 etc.

我让宏按预期工作,但它需要很长时间才能运行。我认为是循环内的偏移减慢了速度。有人有任何建议来加快速度吗?也欢迎任何一般性反馈。

Sub Tiers()

'Input Box
Dim Square As Integer
Square = InputBox("Enter Number of Tiers")
Range("f5").Select
Selection.Value = 0
With Application
.ScreenUpdating = False
End With

'Rows down
Dim g As Integer
Dim h As Integer
Dim i As Integer
Dim j As Integer

'Start For loops
For g = 1 To Square
For h = 0 To Square
For i = 0 To Square
For j = 0 To Square

'calculate offsets and place values of loop variables
Dim step As Long
step = ((g - 1) * (Square + 1) ^ 3 - 1 + (h * (Square + 1) ^ 2) + Square * i + i + j + 1)
Selection.Offset(step, 0).Value = j
Selection.Offset(step, -1).Value = i
Selection.Offset(step, -2).Value = h
Selection.Offset(step, -3).Value = g


Next j
Next i
Next h
Next g

With Application
.ScreenUpdating = True
End With

End Sub

谢谢

最佳答案

根据我在您的帖子下面的评论,循环和写入这样的工作表会太慢。写入数组,然后将数组写入工作表。眨眼间就完成了。

这就是你正在尝试的吗?

Sub Sample()
Dim TempArray() As Long
Dim n As Long
Dim g As Long, h As Long, i As Long, j As Long
Dim reponse As Variant

'~~> Accept only numbers
reponse = Application.InputBox(Prompt:="Enter Number of Tiers", Type:=1)

If reponse <> False Then
For g = 1 To reponse
For h = 0 To reponse
For i = 0 To reponse
For j = 0 To reponse
n = n + 1
Next j
Next i
Next h
Next g

ReDim Preserve TempArray(1 To n, 1 To 4)
n = 1

For g = 1 To reponse
For h = 0 To reponse
For i = 0 To reponse
For j = 0 To reponse
TempArray(n, 1) = g
TempArray(n, 2) = h
TempArray(n, 3) = i
TempArray(n, 4) = j
n = n + 1
Next j
Next i
Next h
Next g

'~~> Replace this with the relevant sheet
Sheet1.Range("A1").Resize(UBound(TempArray), 4).Value = TempArray
End If
End Sub

屏幕截图:

enter image description here

关于循环内的 VBA 偏移 - 需要永远运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52612618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com