条件满足后代码仍然循环

时间:2016-12-19 15:33:22

标签: excel vba excel-vba

在下面的代码中,即使满足条件,循环也会保持循环。当我逐行运行并最初运行循环时,我可以看到单元格选择从J300开始的位置,我可以看到选择向下移动到列,但是当它到达满足条件的单元格时,选择不再偏移,但代码继续循环,它不会转到下一行。我做错了什么,我该怎么做才能让它变得更好?谢谢你的帮助。

Sub RollForwardDataImport()
Dim rcell5, rcell6, rcell7, rcell8, rcell9 As Long
  rcell8 = 0
  rcell5 = Range("F2").Value
  rcell9 = Range("F2").Value
  Workbooks.Open "\\Inventory\CA-2016.xlsx"
  Worksheets("Total Year").Activate
  Range("J300").Select

  Do While Selection.Value <> recell5
    If Selection.Value = rcell5 Then 
      ActiveCell.Offset(0, 0).Select
    Else: ActiveCell.Offset(1, 0).Select
    End If
  Loop
  ActiveCell.Offset(0, -2).Select
  rcell6 = Selection.Value
  ActiveCell.Offset(0, -4).Select
  rcell7 = Selection.Value
  rcell8 = rcell6 + rcell7 + rcell8

  Workbooks("Import.xlsm").Activate
  Range("H20").Select
  ActiveCell.Value = rcell8
  Workbooks("CA-2016.xlsx").Close SaveChanges:=False
End Sub

1 个答案:

答案 0 :(得分:1)

这是您的代码的调整版本。请注意,它避免使用.Select / .Activate,并且还使用循环来查找您的值。

我强烈建议单步执行 F8 ,以便逐行查看代码的工作原理。

Option Explicit
Sub RollForwardDataImport()
Dim rcell5 As Date, rcell6 As Long, rcell7 As Long, rcell8 As Long, rcell9 As String
rcell8 = 0
rcell5 = 11/1/2016 'Range("F2").Value
rcell9 = Range("F2").Value

Workbooks.Open "\\Inventory\CA-2016.xlsx"

Dim myRng As Range, cel As Range

With Worksheets("Total Year")
    Set myRng = Range("J300:J1000")    'change this to your need. May be farther than row 1000

    For Each cel In myRng
        If cel.Value = rcell5 And Month(cel.Vlaue) = Month(rcell5) Then
            rcell6 = cel.Offset(0, -2).Value
            rcell7 = cel.Offset(0, -4).Value
            rcell8 = rcell6 + rcell7 + rcell8
            rcell5 = rcell5 + 
            Exit For
        Else
           rcell5 = cell.Offset(1,0).Value
        End If
    Next cel
End With

With Workbooks("Import.xlsm")
    .Range("H20").Value = rcell8
End With

Workbooks("CA-2016.xlsx").Close SaveChanges:=False
End Sub

它应该按照你的意愿工作,但我可能错过了一些东西。如果是这样,请告诉我。