简体   繁体   中英

How to fix loop initializing only some of the time in Excel VBA?

I have an excel VBA macro that transfers some data from one workbook to another. The workbook that the data is sent to is set up with 12 worksheets, each one representing a month. When the user initiates the macro, it determines which sheet to paste the data into from some of the data being transferred. I bring this up because the issue I am having is dependent on the sheet the data will be pasted to. Part of the macro is a do while loop that finds the next available row to paste the data to. This loop only activates on certain sheets. The loop is skipped in other sheets. (For example, the loop will activate if the data will be pasted into the December sheet but not the November sheet or the January Sheet.)

I have stepped through the macro two times. The first time I set the the data to be pasted to the december sheet and the loop worked correctly.

The second time I set the data to be pasted in the January sheet and the loop was skipped over.

With wbOut.Sheets(strSheet)
        .Activate
        nLastRowOut = .Range("A500").End(xlUp).Row + 1
        i = 220
        nLastRowOut = i
        Do While (i > 41)
              str = .Range("A" & i).Value & .Range("B" & i).Value & .Range("C" & i).Value & .Range("D" & i).Value & .Range("E" & i).Value & .Range("F" & i).Value & .Range("G" & i).Value & .Range("H" & i).Value & .Range("I" & i).Value & .Range("J" & i).Value & .Range("K" & i).Value & .Range("L" & i).Value & .Range("M" & i).Value
              If Replace(str, 0, "") <> "" Then
                    nLastRowOut = i + 1
                    GoTo copySections
              End If
              i = i - 1
        Loop

The next available row should be found and and then used to paste the data.

What is actually happening 75% of the time is that the loop is skipped over and the data is pasted in row 221 instead of the next available row.

The code for the nLastRowOut doesn't look right..

Change this:

nLastRowOut = .Range("A500").End(xlUp).Row + 1

to this:

nLastRowOut = .Range("A" & Rows.Count).End(xlUp).Row + 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM