mercredi 13 février 2019

How do I use a macro to copy and paste in the same row if a condition is met?

I'm still new to VBA and I'm running a report and the way I receive it a few of the rows have an additional column of data that I don't need but it messes up formatting for those entries. For example, in Column B I have the profiles listed for everyone but for these few entries I have a number or something else (it isn't consistent for each one). But for those same entries I have a "Y" in Column H that none of the other entries have. I'm trying to search through the report for the "Y" in Column H and then copy columns C through H and paste it in Column B so that all the data aligns. Out of a couple hundred entries there might be 6-7 that need to be moved. Here is some sample data that I hope shows the issue. BTHOMAS Column B is the problem in this example.

   A      |    B     |    C    |    D       |    E      |    F      |     G     |   H
--------------------------------------------------------------------------------------------
  ID      | PROFILE  | STATUS  | DATE ADDED | LAST USED | EXP DATE  |  P/W EXP  |
  SBUTLER | NOM      | ENABLED | 9/9/2014   | 10/5/2018 | 00/00/00  |  N        |
  WPERRY  | NOM      | ENABLED | 10/29/2014 | 10/4/2018 | 00/00/00  |  N        |
  BTHOMAS | 1234     | NOM     | ENABLED    | 2/1/2017  | 9/28/2018 |  00/00/00 | Y


I've done a lot of research on copy and paste macros, but everything I have found is either a single cell or the entire row and they paste it to another sheet. I just want to copy and paste in the same row. Here is the code I have so far, unfortunately it moves every column.

Sub MoveColumns()

LR = Cells(Rows.Count, "B").End(xlUp).Row
a = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

    For i = 2 To a

        If Worksheets("Sheet1").Cells(i, 8).Value = "Y" Then
            Range("C:H").copy Range("B:G")

        End If

    Next

End Sub

The expected result is for the report to be aligned like in the example below. There is data in columns I through J so I can only copy columns C through H. Thanks for your time.

 A      |    B     |    C    |    D       |    E      |    F      |     G     |   H
--------------------------------------------------------------------------------------------
  ID      | PROFILE  | STATUS  | DATE ADDED | LAST USED | EXP DATE  |  P/W EXP  |
  SBUTLER | NOM      | ENABLED | 9/9/2014   | 10/5/2018 | 00/00/00  |  N        |
  WPERRY  | NOM      | ENABLED | 10/29/2014 | 10/4/2018 | 00/00/00  |  N        |
  BTHOMAS | NOM      | ENABLED | 2/1/2017   | 9/28/2018 | 00/00/00  |  Y

Aucun commentaire:

Enregistrer un commentaire