转到下一栏

时间:2016-07-28 06:35:49

标签: vba excel-vba excel

任何人都可以帮我解决我的问题吗? 我有这个代码,如果条件不满足,我想转到下一栏。我被困住了,不知道从哪里开始。

Dim lrow3, lrow1 as long
dim dDate as Date
dim yrNum, j as Integer

dDate = Format(Now(),"mm/dd/yyyy")

lrow3 = ActiveSheet.Cells(Rows.count, 2).End(xlUp).Row
lrow1 = Sheets("Sample").Cells(Rows.count, 2).End(xlUp).Row
for j = 2 to lrow1
For yrNum = 1 To 100
    If DateValue(Format(Range("Q" & j).Value, "mm/dd/yyyy")) >= DateValue(dDate) And _
    DateValue(Format(Range("R" & j).Value, "mm/dd/yyyy")) <= DateValue(dDate) Then
    ActiveSheet.Range("D" & lrow3 + 1).Value = Range("T" & j).Value
    ActiveSheet.Range("E" & lrow3 + 1).Value = Range("U" & j).Value
    Exit For
    Else
         Range("Q" & j) = ActiveCell
         Range("Q" & j) = ActiveCell.Offset(0, 9)
    'after executing this is I have to set this offsetted cell to be the active one 
     'on which i will be referring in the next loop
    End If

Next yrNum
next j

在代码段中,如果Q & j中的值不符合要求,那么我必须检查Q之后的第9个字母,即Z,依此类推。 顺便说一下,我在这里比较的是单元格中的日期值。

1 个答案:

答案 0 :(得分:0)

一些观察

  • dDate = Format(Now(),"mm/dd/yyyy")dDate = Date
  • 相同
  • DateValue(Format(Range("Q" & j).Value, "mm/dd/yyyy")) is the same as DateValue(范围(&#34; Q&#34;&amp; j).Value)`
  • 您将从Q列开始,如果条件不符合,则移动9列并再次检查。你这样做了100次。最后一列是第917栏(列字母代码AIG)
Sub RefactoredCode()

    Dim lrow3, lrow1 As Long
    Dim DateRange As Range
    Dim wsSample As Worksheet
    Dim yrNum, j As Integer, iOffset As Integer

    Set wsSample = Worksheets("Sample")

    lrow3 = Cells(Rows.Count, 2).End(xlUp).Row
    lrow1 = wsSample.Cells(Rows.Count, 2).End(xlUp).Row

    For j = 2 To lrow1
        For yrNum = 1 To 100

            iOffset = (yrNum * 9) - 9
            Set DateRange = wsSample.Cells(j, "Q").Offset(0, iOffset)

            If DateValue(DateRange.Value) >= Date And _
               DateValue(DateRange.Offset(0, 1).Value) <= Date Then
                lrow3 = lrow3 + 1
                Range("D" & lrow3).Value = wsSample.Cells(j, "T").Offset(0, iOffset).Value
                Range("E" & lrow3).Value = wsSample.Cells(j, "U").Offset(0, iOffset).Value
                Exit For
            End If

        Next yrNum
    Next j

End Sub