VBA:循环不包括最后2行

时间:2017-04-27 07:52:52

标签: excel vba excel-vba

问题: 我有一个代码可以完成它应该做的一切,只是它没有“完成”它的工作。每当我运行此代码时,似乎不包括最后两行。

代码:

Sub List()

Dim sStDev As Worksheet: Set sStDev = Sheets("StDev")
Dim sResult As Worksheet: Set sResult = Sheets("Large")
Dim sQuart As Worksheet: Set sQuart = Sheets("Quintile")
Dim sReturn As Worksheet: Set sReturn = Sheets("Return")

Dim j As Long

Const colDate As Long = 1
Const rowStDevFirst As Long = 2
Const rowResultFirst As Long = 2
Dim LastRow As Long
LastRow = sReturn.Cells(Rows.Count, "A").End(xlUp).Row
Dim rowResult As Long: rowResult = rowResultFirst

j = 2

Dim i As Long: For i = rowStDevFirst To LastRow

Dim colResult As Long: colResult = 1
sResult.Cells(rowResult, colResult).Value = sStDev.Cells(i, colDate).Value
colResult = colResult + 1

For j = 1 To 792
If sStDev.Cells(i, j).Value >= sQuart.Range("F2").Offset(i, 0) And sStDev.Cells(i, j).Value <= sQuart.Range("G2").Offset(i, 0) Then
    sResult.Cells(rowResult, colResult).Value = sReturn.Cells(i, j).Value
colResult = colResult + 1

End If


Next j

rowResult = rowResult + 1

Next i

MsgBox "Listed"


End Sub

如何让这段代码包含我的最后两行呢?

提前谢谢!

档案:File

1 个答案:

答案 0 :(得分:0)

正如我所见,您尝试使用返回表中的这些值填充大表单,其中StDev中的相应值介于每行的Quintile中的F和G值之间。

没关系,但是你不应该用N来抵消Quintile中的值,即使是第二行你也得到了Quintile!F4和G4而不是F2和G2。

要解决此问题,您应该将sQuart.Range("F2").Offset(i, 0)更改为sQuart.Range("F2").Offset(i-2, 0)

和G列相同:Offset(i, 0)应为Offset(i-2, 0)