VBA:第二个循环覆盖第一个循环

时间:2013-12-31 16:01:03

标签: excel loops excel-vba vba

快速,我认为,在Excel中有关VBA的相对简单的问题。我正在编写我的第一个嵌套循环,我遇到了第二个增量覆盖第一个增量的问题。这是代码:

Sub RandNumRang()
Dim i As Integer, Row As Integer, Col As Integer
Dim j As Integer
Dim LastRow As Long
Dim NoRows As Integer
Dim MinNum As Double, MaxNum As Double
Dim NumFormula As String
Col = 1 'Write random numbers on Column A
'Get the range and number of random values needed
For j = 3 To 4
    NoRows = ActiveSheet.Range("G" & j).Value 'No of random values needed
    MinNum = ActiveSheet.Range("E" & j).Value 'Min Range
    MaxNum = ActiveSheet.Range("F" & j).Value 'Max Range
    NumFormula = "=RANDBETWEEN(" & MinNum & "," & MaxNum & ")" 'Generate between Range
    i = 0
    For Row = 2 To NoRows + 1
    i = i + 1
        ActiveSheet.Cells(Row, Col).Value = i 'ID
        ActiveSheet.Cells(Row, Col + 1).Formula = NumFormula 'Random Value
        ActiveSheet.Cells(Row, Col + 2).FormulaR1C1 = "=TIME(0,0,RC[-1])" 'Convert to time
    Next Row
Next j
End Sub

我正在尝试生成一组随机时间间隔。除了我的值被覆盖之外,代码完全按照我的要求执行。 j 循环最终将具有2个以上的增量,但无论如何,此代码都将具有相同的覆盖问题。我很确定它与我指定

有关
For Row=2 To NoRows + 1 

作为嵌套循环的起点,但这又是我第一次在VBA脚本上运行,我想我会伸出手,因为我尝试过的每个修复都失败了。在此先感谢,如果您需要任何进一步的细节,请告诉我。

另外,我附上了工作表的截图供参考:

enter image description here

2 个答案:

答案 0 :(得分:4)

据我所知,它的表现正如预期一样。你设置:

 Col = 1

然后两个循环保持相同。然后你有:

For Row = 2 To NoRows + 1

所以在你的第二个循环中,你总是会从第2行第1列开始,所以它总是会被覆盖。

你需要在第二次迭代中将Col设置为4(或5),否则跟踪你在行中的位置并追加到末尾,

答案 1 :(得分:2)

这适用于您的示例:

Sub RandNumRang()
Dim Row As Integer, Col As Integer
Dim j As Integer
Dim LastRow As Long
Dim NoRows As Integer
Dim MinNum As Double, MaxNum As Double
Dim NumFormula As String
Col = 1
Row = 2

For j = 3 To 4
    NoRows = Range("G" & j).Value
    MinNum = Range("E" & j).Value
    MaxNum = Range("F" & j).Value
    NumFormula = "=RANDBETWEEN(" & MinNum & "," & MaxNum & ")"

    For Row = Row To (Row + NoRows - 1)
        Cells(Row, Col).Value = Row - 1
        Cells(Row, Col + 1).Formula = NumFormula 'Random Value
        Cells(Row, Col + 2).FormulaR1C1 = "=TIME(0,0,RC[-1])" 'Convert to time
    Next Row
Next j
End Sub