Full Version: Copy And Paste
UtterAccess Discussion Forums > Microsoft® Office > Microsoft Excel
John_Ross
Hi,

I want to develop a macro where:

1. It will copy specific State’s information from “Sheet1” in “File A – Mar12.xls”
2. It will paste the information in “Sheet2” in the specific State file.

For example:
“Sheet1” in “File A – Mar12.xls”

State City Name Contact
New York Buffalo Sam xzyiqwiqp
Penn Philly Tam fhskfksj
Penn Pitt Jam kcpsaf[s
New York NYC Lam kdasld[‘A

I want it to copy any rows that belongs to the state of New York from the above file and paste it into “Sheet2” of “New York – Mar12.xls”. I want it to only copy “Column City to Column Contact” I do not want it to copy the State Column above. Also I want it to paste in cell C10 in “Sheet2”.

Some things to keep in mind:

The folder name and file name for the state files changes every month – Mar12, Apr12 etc. For the “File A” only the name changes each month. The folder remains the same. Currently the files are located here:

FILE A
C:Desktop\File A\

State Files
C:Desktop\State Files\Mar12

I want to operate this macro from a third unrelated sheet.

Thank you.
darnellk
Is there something specific you want help with? What you're asking seems fairly simple if your directory and file naming structure will not change. Have you tried using the Macro recorder to get your basic steps?

It looks like you will need to loop through your list of states and create a unique list, then use that list to loop through each state and filter your records which you can then copy and paste into the new file sheet 2.

Will this state-month-year file already be created and have something in Sheet1 before you perform your copy paste action?
John_Ross
Hi,

Both File A and the State files have been already created. I just want to cut and paste from one file to another. I did not try the macro recorder since I will for example only get a basic copy and paste one row to another.

Thank you.
Bob G
is this a one time exercise?

if you do record the macro, even if just for one row, you can then modify the vba to loop and such .
John_Ross
Hi,

As per your suggestions, I recorded the macro. How do I add the loop and make the macro find which month’s folder / file name it should be looking at?

CODE
Sub Macro1()
    Windows("File A - Mar12.xls").Activate
    Application.Run "OnWindow"
    Range("D11:G11").Select
    Selection.Copy
    Windows("New York – Mar12.xls").Activate
    Application.Run "OnWindow"
    Range("C10").Select
    ActiveSheet.Paste
End Sub
Bob G
would it be possible to put together a little sample of the data and zip it and upload it?

just enough information in the exact columns to be able to identify the what and where and when
John_Ross
Yes. Will do so tonight.
Bob G
one other thing, what version of Excel ??
John_Ross
2003
darnellk
Try this for a start. I can't seem to get the code working to check if the State workbook is open or not, so I've commented some of it out, and it just opens the workbooks regardless (if you have the workbooks closed, it will work). You may want to add some code to save and close the workbooks when complete. This assumes that your State is in column "A", city in column "B", etc. of Sheet1 - you will need to adjust if not.

CODE
Sub CopyToStateFile()
    
    Dim lngFirstRow As Long
    Dim lngLastRow As Long
    Dim lngUniqueStateRow
    Dim strMonthYear As String
    Dim strState As String
    Dim varStateWorkbookName As Variant
    Dim wbkStateWorkbook As Workbook
    
    ' turn off screen updates during the copy/paste process
    Application.ScreenUpdating = False
    
    ' get the month and year that File A is named as right now
    strMonthYear = Mid(ThisWorkbook.Name, 10, 5)
    
    ' copy the state column to Sheet 3 temporarily and then filter the Sheet3 list for unique states
    Sheets("Sheet3").Range("A:A").Value = Sheets("Sheet1").Range("A:A").Value
    Sheets("Sheet3").Columns("A:A").AdvancedFilter Action:=xlFilterInPlace, Unique:=True
    
    ' set the starting row number to row 2 - after the 'State' heading
    lngUniqueStateRow = 2
                              
    ' Select cell A2, *first row of state data*.
    Sheets("Sheet3").Select
    Range("A" & lngUniqueStateRow).Select
                
    ' Loop through states until the end of the list is found
    Do Until IsEmpty(ActiveCell)
                
        ' check if current row is hidden/filtered or not
        If Rows(lngUniqueStateRow).Hidden = True Then
        
            ' the row is hidden/filtered, so skip it
            GoTo NextRow
            
        End If
        
        ' set State variable
        strState = Worksheets("Sheet3").Range("A" & lngUniqueStateRow)
        
        ' filter the state data in Sheet1
        Sheets("Sheet1").Select
        Rows("1:1").Select
        Selection.AutoFilter Field:=1, Criteria1:=strState
        
        ' find the first row with data
        Range("A1").Select
        lngFirstRow = Selection.Offset(1, 0).Row
        
        ' find the last row with data
        lngLastRow = Cells(Rows.Count, 1).End(xlUp).Row
        
        ' select the top left to the bottom right range of data from the second column, then copy the range
        Range("B" & lngFirstRow & ":D" & lngLastRow).Select
        Selection.Copy
        
        ' set State Workbook name
        varStateWorkbookName = strState & " - " & strMonthYear & ".xls"
        
        ' Open state workbook if it is not already, otherwise just activate it.
        'If Len(Workbooks(varStateWorkbookName).Name) > 0 Then
            
            Workbooks.Open Filename:= _
                "C:\Desktop\State Files\" & strMonthYear & "\" & varStateWorkbookName
                
        'Else
        
            'Windows(varStateWorkbookName).Activate
            'Application.Run "OnWindow"
            
        'End If
        
        ' paste the copied data into the state workbook
        Sheets("Sheet2").Select
        Range("C10").Select
        ActiveSheet.Paste
        
        Windows(ThisWorkbook.Name).Activate
        Application.CutCopyMode = False
        
NextRow:
        ' Step down 1 row from present location.
        lngUniqueStateRow = lngUniqueStateRow + 1
        
        ' go back to temporary sheet3 data
        Sheets("Sheet3").Select
        
        ' Select next cell (state)
        Range("A" & lngUniqueStateRow).Select
                
    Loop
    
    ' clean up temporary data in sheet 3
    Sheets("Sheet3").Select
    ActiveSheet.ShowAllData
    Columns("A:A").Select
    Selection.ClearContents
    
    ' go back to Sheet 1 and remove filter
    Sheets("Sheet1").Select
    ActiveSheet.ShowAllData
    
    ' turn on screen updates during the copy/paste process
    Application.ScreenUpdating = True
    
End Sub
John_Ross
Hi Darnell,

I really appreciate that you wrote a lenghty code for this. I tried your code and customized it but I'm getting run time error 1004. It seems to be partially working as it opened my New York file and it copied some of the information. Attached are the sample files that I'm using.
darnellk
What does the rest of the error say? If you only have a file for New York and not the other states, it will error because it cannot open the other files.

As I said earlier, I do not have the code working to check if a workbook is already open or does not exist - therefore you will get an error if one of these cases exist. Perhaps someone else can help in this regard.

I've updated all of the cell references so that is pasting the right data in the right place now.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.