10

使用 Excel (2010) VBA,我试图将恒定范围的单元格(其值重新计算)复制(传递)到数组中。然后我试图将该数组传递给一个新的单元格范围,就在它的正下方。完成此操作后,我想再次将常量范围的新值复制(传递)到数组,并将这些新值传递到直接低于我之前传递的范围的范围。

我知道这段代码很糟糕(我对 VBA 中的数组不熟悉)。

Sub ARRAYER()

Dim anARRAY(5) As Variant

Number_of_Sims = 10

For i = 1 To Number_of_Sims
   anARRAY = Range("C4:G4")
   Range("C4").Select
   ActiveCell.Offset(Number_of_Sims, 0).Select
   ActiveCell = anARRAY
   Range("C4").Select
Next

End Sub

我非常感谢您的帮助!

谢谢你。

尊敬,

乔纳森

4

4 回答 4

9

您在这里的一些事情上略有偏差,因此希望以下内容有所帮助。

首先,您不需要选择范围来访问它们的属性,您只需指定它们的地址等。其次,除非您正在操作范围内的值,否则您实际上不需要将它们设置为变体。如果您确实想操作这些值,则可以省略数组的边界,因为它会在您定义范围时设置。

Option Explicit在模块顶部使用强制变量声明也是一种很好的做法。

以下将做你所追求的:

Sub ARRAYER()
    Dim Number_of_Sims As Integer, i As Integer

    Number_of_Sims = 10

    For i = 1 To Number_of_Sims
       'Do your calculation here to update C4 to G4
       Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = Range("C4:G4").Value
    Next
End Sub

如果您确实想操作数组中的值,请执行以下操作:

Sub ARRAYER()
    Dim Number_of_Sims As Integer, i As Integer
    Dim anARRAY as Variant

    Number_of_Sims = 10

    For i = 1 To Number_of_Sims
       'Do your calculation here to update C4 to G4
       anARRAY= Range("C4:G4").Value

       'You can loop through the array and manipulate it here

       Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = anARRAY
    Next
End Sub
于 2013-02-10T04:14:13.037 回答
3

不需要数组。只需使用这样的东西:

Sub ARRAYER()

    Dim Rng As Range
    Dim Number_of_Sims As Long
    Dim i As Long
    Number_of_Sims = 10

    Set Rng = Range("C4:G4")
    For i = 1 To Number_of_Sims
       Rng.Offset(i, 0).Value = Rng.Value
       Worksheets("Sheetname").Calculate   'replacing Sheetname with name of your sheet
    Next

End Sub
于 2013-02-10T04:17:03.923 回答
2

由于您将相同的数据复制到所有行,因此您实际上根本不需要循环。试试这个:

Sub ARRAYER()
    Dim Number_of_Sims As Long
    Dim rng As Range

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Number_of_Sims = 100000

    Set rng = Range("C4:G4")
    rng.Offset(1, 0).Resize(Number_of_Sims) = rng.Value

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub
于 2013-02-10T09:00:57.130 回答
0

当我尝试您的代码时,当我想填充数组时出现错误。

您可以尝试像这样填充数组。

Sub Testing_Data()
Dim k As Long, S2 As Worksheet, VArray

Application.ScreenUpdating = False
Set S2 = ThisWorkbook.Sheets("Sheet1")
With S2
    VArray = .Range("A1:A" & .Cells(Rows.Count, "A").End(xlUp).Row)
End With
For k = 2 To UBound(VArray, 1)
    S2.Cells(k, "B") = VArray(k, 1) / 100
    S2.Cells(k, "C") = VArray(k, 1) * S2.Cells(k, "B")
Next

End Sub
于 2016-07-01T11:40:48.007 回答