如果我试图概括这一点,那么for循环应该如何:
给出Number = 3
FirstCellToWrite.Value = Controls("txtBox" & 1).Text
FirstCellToWrite.Offset(1, 0).Value = Controls("txtBox" & 2).Text
FirstCellToWrite.Offset(2, 0).Value = Controls("txtBox" & 3).Text
FirstCellToWrite.Offset(0, 1).Value = Controls("txtBox" & 4).Text
FirstCellToWrite.Offset(1, 1).Value = Controls("txtBox" & 5).Text
FirstCellToWrite.Offset(2, 1).Value = Controls("txtBox" & 6).Text
FirstCellToWrite.Offset(0, 2).Value = Controls("txtBox" & 7).Text
FirstCellToWrite.Offset(2, 2).Value = Controls("txtBox" & 9).Text
FirstCellToWrite.Offset(1, 2).Value = Controls("txtBox" & 8).Text
我尝试的是:
q= 0
For p = 1 To number
For i = 0 To number - 1
FirstCellToWrite.Offset(i, q).Value = Controls("txtBox" & p).Text
Next i
q = q+1
Next p
但这不起作用
答案 0 :(得分:3)
在没有q或i的情况下尝试它,并在p。
上进行一些数学运算For p = 0 To number - 1
debug.print "i=" & p mod 3 & ", q=" & int(p/3) & ", p=" & p+1
FirstCellToWrite.Offset(p mod 3, int(p/3)).Value = Controls("txtBox" & p+1).Text
Next p
立即窗口结果:
i=0, q=0, p=1
i=1, q=0, p=2
i=2, q=0, p=3
i=0, q=1, p=4
i=1, q=1, p=5
i=2, q=1, p=6
i=0, q=2, p=7
i=1, q=2, p=8
i=2, q=2, p=9
答案 1 :(得分:2)
如果你简化它,只使用1个循环:
For p = 0 To (number-1)\3 'Using \ instead of / returns just the integer part
'i.e. 1/2 = 0.5, 1\2 = 0 and 5/2 = 2.5, 5\2 = 2
FirstCellToWrite.Offset(0, p).Value = Controls("txtBox" & (3*p + 1)).Text
FirstCellToWrite.Offset(1, p).Value = Controls("txtBox" & (3*p + 2)).Text
FirstCellToWrite.Offset(2, p).Value = Controls("txtBox" & (3*p + 3)).Text
Next p
然后,更容易看到如何使内部成为第二个循环:
For p = 0 To (number-1)\3
For i=1 To 3
FirstCellToWrite.Offset(i-1, p).Value = Controls("txtBox" & (3*p + i)).Text
Next i
Next p
答案 2 :(得分:1)
尝试使用以下内容:
Dim ctrl As Long, RowCount As Long, ColumnCount As Long, IncrementCounter As Long
IncrementCounter = 3
For ctrl = 1 To 9
FirstCellToWrite.Offset(RowCount, ColumnCount).Value2 = Controls("txtBox" & ctrl).Text
RowCount = RowCount + 1
If ctrl Mod IncrementCounter = 0 Then
ColumnCount = ColumnCount + 1
RowCount = 0
End If
Next ctrl
答案 3 :(得分:0)
我认为你的p和q应该是相反的:
FirstCellToWrite.Offset(i,p).value = Controls("txtBox" & q).Text
q = q + 1
应位于“i”for循环之间。