+ Reply to Thread
Results 1 to 36 of 36

error message when Automating copy/paste worksheets

Hybrid View

  1. #1
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    error message when Automating copy/paste worksheets

    Hello all,
    I have been working on this macro all day and no matter how many different ways I write it I can't seem to get it to finish correctly without giving me an error message. The error messages are different depending on how I write the macro, so what the message says is not important.

    I have attached a sample of my work which contains the macro, but I'll post the code below as well. There are two tabs in the workbook. One contains the data("download") and the other is the template("Blank") per say. I need the macro to create a new worksheet using the template for each line of the data ("download")until it gets to the "finalrow." It names the worksheets the value of D3 currently, but I'd like to figure out how to name the worksheets by C3. c3 contains the names of customers, and is duplicated for each product they have purchased. I'd just like to attach a number after the name if it is a duplicate. i.e. Adam, Adam1, Adam2, Adam3 for all "Adam"s.

    Look into the code and see if that makes sense. if not, feel free to ask questions. I appreciate the time you take to help me resolve this issue!

    thanks

    Sub automate_linesheets()
    '
    ' automate_linesheets Macro
    ' Macro recorded 10/8/2009 by Kelly.Householder
    '
    
    Dim finalrow As Long
    Dim finalcolumn As Long
    
        Sheets("Download").Select
        ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Select
        finalrow = ActiveCell.Row
        Debug.Print finalrow
        finalcolumn = ActiveCell.Column
        Debug.Print finalcolumn
    
        Sheets("Download").Select
        Range("C3").Select
        Range(Cells(3, 1), Cells(finalrow, finalcolumn)).Sort Key1:=Range("C3"), Order1:=xlAscending, Key2:= _
            Range("D3"), Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, _
            Orientation:=xlTopToBottom, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal
    
    'Range(Cells(3, 1), Cells(finalrow, 30))
    Dim I As Long
        
        For I = 3 To finalrow
        Sheets("Download").Select
        Cells(I, 2).Select
            If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
               Range(Cells(I, 1), Cells(I, 34)).Select
               'Rows(I).EntireRow.Select
               Selection.Copy
               Sheets("Blank").Select
               Range("A3").Select
               ActiveSheet.Paste
               Sheets("Blank").Select
               Sheets("Blank").Copy After:=Sheets(2)
               ActiveSheet.Name = Range("D3")
               'On Error Resume Next
            End If
         
         Next I
    
    End Sub
    Attached Files Attached Files
    Last edited by curbster; 10-09-2009 at 08:03 PM.

  2. #2
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    im not sure though i think this may do what you want
    Sub automate_linesheets()
    '
    ' automate_linesheets Macro
    ' Macro recorded 10/8/2009 by Kelly.Householder
    '
    
    Dim finalrow As Long
    Dim finalcolumn As Long
    
        finalrow = Sheets("Download").Cells.SpecialCells(xlCellTypeLastCell).Row
        Debug.Print finalrow
        finalcolumn = ActiveCell.Column
        Debug.Print finalcolumn
    
     '   Sheets("Download").Range(Cells(3, 1), Cells(finalrow, finalcolumn)).Sort Key1:=Range("C3"), Order1:=xlAscending, Key2:= _
            Range("D3"), Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, _
            Orientation:=xlTopToBottom, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal
    
    'Range(Cells(3, 1), Cells(finalrow, 30))
    Dim I As Long
        
        For I = 3 To finalrow
        Sheets("Download").Select
        Cells(I, 2).Select
            If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
               Range(Cells(I, 1), Cells(I, 34)).Copy
               Sheets("Blank").Range("A3").PasteSpecial xlAll
               Sheets("Blank").Select
               Sheets("Blank").Copy After:=Sheets(2)
               ActiveSheet.Name = Range("D3")
               'On Error Resume Next
            End If
         
         Next I
    
    End Sub
    you can do the sort
    by adding a filter to the range

  3. #3
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    Hi, I still am receiving the same error once the macro has created about 60 tabs. the error is:

    "Run-time error '1004':

    The sheet you are copying has cells tha contain more than 255 characters. When you copy the entire sheet, only the first 255 characters in each cell are copied.

    To copy all of the characters, copy the cells to a new sheet instead of copying the entire sheet."



    D_Rennie, I appreciate your help, your code gives me the same result as my code. Any idea on this error message what to do?

    Thanks!

    P.S.~ I've attached a copy of the error message with this post.
    Attached Images Attached Images

  4. #4
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    Hello Curbster.

    try
    Sub automate_linesheets()
    Dim finalrow As Long
    Dim finalcolumn As Long
    Dim shtnum As Long
        finalrow = Sheets("Download").Cells.SpecialCells(xlCellTypeLastCell).Row
        Debug.Print finalrow
        finalcolumn = ActiveCell.Column
        Debug.Print finalcolumn
        
    Dim I As Long
        For I = 3 To finalrow
        Sheets("Download").Select
        Cells(I, 2).Select
            If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
            shtnum = 1
               Range(Cells(I, 1), Cells(I, 34)).Copy
               Sheets("Blank").Range("A3").PasteSpecial xlAll
               Sheets("Blank").Select
               Sheets("Blank").Copy After:=Sheets(2)
               If SheetExists(Range("C3")) Then
    CheekShtName:
                    If SheetExists(Range("C3") & shtnum) Then
                        shtnum = shtnum + 1
                        GoTo CheekShtName
                    Else
                        ActiveSheet.Name = Range("C3") & shtnum
                    End If
               Else
               ActiveSheet.Name = Range("C3")
               End If
               'On Error Resume Next
            End If
         Next I
    End Sub
    
    Function SheetExists(SheetName As String) As Boolean
    ' returns TRUE if the sheet exists in the active workbook
        SheetExists = False
        On Error GoTo NoSuchSheet
        If Len(Sheets(SheetName).Name) > 0 Then
            SheetExists = True
            Exit Function
        End If
    NoSuchSheet:
    End Function
    sheets are based on customer name (C3). if sheets y exist it adds 1 to the num then 2......
    Is the intent to have one page with only one line of variable data.
    If so can i ask why it seams that you are ending up with lots of sheet doing things like this (192 for the sample data alone). I would end up getting lost with that many sheets.

    anyhow
    hope this helps/

  5. #5
    Forum Expert royUK's Avatar
    Join Date
    11-18-2003
    Location
    Derbyshire,UK
    MS-Off Ver
    Xp; 2007; 2010
    Posts
    26,200

    Re: error message when Automating copy/paste worksheets

    Why would you want one sheet for each line?
    Hope that helps.

    RoyUK
    --------
    For Excel Tips & Solutions, free examples and tutorials why not check out my web site

    Free DataBaseForm example

  6. #6
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    D_Rennie,
    Thanks again for the help, it is still returning the same error. I think I will need to change this procedure to save a seperate workBOOK instead of workSHEET.

    A little background as to why I am creating these new sheets for each line: for security reasons I have deleted a template below the line that I copy into each sheet. It contains a page of information which plugs in the criteria into its respective line (i.e. customer name, account number, address, etc). That is one reason why I'm getting a different error message than I do with the sample excel file I posted to the forum. However, the error comes at the same time (after it has created about 58 sheets), it just is completely different error.

    The reason why we wanted to have one sheet per customer is because we print them off and organize them with paper records we keep. We do not constantly flip through the tabs (I would get lost too if that were the case) but we did want to save them all together.

    This sample has more lines than we normally have, but this one branch I'm working on has as many lines as the sample, which is why I'm running into the errors. Is excel limited on the number of worksheets it contains within one workbook?

    If anyone could help me to save these into seperate workbooks instead of new tabs that would be great! The same rules would apply for duplicates, just by adding a number after a customer name if it has already been saved.

    When saving into a new workbook, I will only need the contents of the "blank" tab as the workbook and not the data "download" tab. In other words, if the newly created workbook files could exlude the "download" tab that is preferred.

    thanks again for previous and future help on this!
    Last edited by curbster; 10-13-2009 at 12:35 PM.

  7. #7
    Forum Expert royUK's Avatar
    Join Date
    11-18-2003
    Location
    Derbyshire,UK
    MS-Off Ver
    Xp; 2007; 2010
    Posts
    26,200

    Re: error message when Automating copy/paste worksheets

    Do yo ant a sheet for each unique name in Column C?

  8. #8
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    The code as it stands is correct. So the criteria in the code would determine which lines I need new workbooks for. i.e.

    If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
    Basically as long as both values in columns 11 and 12 are greater than zero, I'll need a new worksheet for that customer.

    does that make sense? I hope I understood the question.

    thanks!

  9. #9
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    So I have to change my procedures and felt it was a worthy of a new thread. After I was locked out of the newer (more clearly stated thread) I decided to repost here on my original thread.

    Here is the followup of my situation: thanks in advance to anyone who can help, this is a duesy!


    "Hi all,

    I have a sample of code below and I need help figuring out how to create and save a new workbook for every line of data with certain criteria. I'll detail it below:

    1. if data in cells (I row) and columns 11 and 12 are both negative numbers, skip row.
    2. if data in those cells are positive numbers, copy entire row and paste into new workbook "Template" in cell A3.
    3. save filename as the value of range("C3")
    -if file exists with that name, add a number to the end (i.e. John, John1, John2)
    4. repeat steps 1-4 until final row.
    5. if data in cells (I row) and columns 11 and 12 are both negative numbers:
    - if I.Row and column 27 (column "AA") is equal to ANY row, column 4 ("D") then:
    - copy I.Row
    - select "Template" workbook
    - insert new row under "C3" and insert contents.
    - repeat until final row.

    Much of this is already in the code, but I've had to make changes because I kept running into an error that would not let me proceed. The code as it stands now copies the I.row into a new worksheet within the same workbook. I've had to change the process and now I need to create new workbooks instead of sheets. I still consider myself in the beginning stages of excel VBA program writing so please help where you can!"

    here is what it looks like when I record it.
     Rows("3:3").Select
        Selection.Copy
        Sheets("Blank").Select
        Rows("3:3").Select
        ActiveSheet.Paste
        Cells.Select
        Application.CutCopyMode = False
        Selection.Copy
        Workbooks.Add
        ActiveSheet.Paste
        Application.CutCopyMode = False
        ActiveWorkbook.SaveAs Filename:= _
            "\\cbl\Users\book1.xls", _
            FileFormat:=xlNormal, Password:="", WriteResPassword:="", _
            ReadOnlyRecommended:=False, CreateBackup:=False
        ActiveWindow.Close
        Sheets("Download").Select
        Rows("5:5").Select
        Selection.Copy
        Sheets("Blank").Select
        Rows("3:3").Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        ChDir "C:\Documents and Settings\Desktop"
        Cells.Select
        Selection.Copy
        Workbooks.Add
        ActiveSheet.Paste
        Application.CutCopyMode = False
        ActiveWorkbook.SaveAs Filename:= _
            "C:\Documents and Settings\Desktop\Book2.xls", FileFormat:= _ 'this should be saved as the value in cell "C3" (there will be duplicate values of C3 which will need to be saved as "C3 & shtnum" or similar)
            xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
            , CreateBackup:=False
    End Sub
    Thanks,
    Curbster

  10. #10
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    Hello Curbster.

    I realy dont understand what you are doing. (Well i understand what the request is though i cant see why).

    You say that the reason that you wanted the sheets to be created like this is that you want to print each sheet off to keep a paper record.
    Now you want to create a new workbook for each record *Same thing lots of workbook 192*

    Also are you wanting to create a new Sheet/Workbook for each customer again with the +1.

    How did the code i provided last go????????
    you can add a print in the loop to print the pages.
    let me know what the code isnt doing and go from there.
    Cheers Dave

    if you just want what the last code provides but with saving the sheets as a new workbook. You can run this sub to save each sheet as a new workbook.
    Copied From Here
    Sub MakeMultipleXLSfromWB()
      'Split worksheets in current workbook into
      ' many separate workbooks  D.McRitchie, 2004-06-12
      'Close each module  AND the VBE before running to save time
      ' provides a means of seeing how big sheets really are
      'Hyperlinks and formulas pointing to other worksheets within
      ' the original workbook will usually be unuseable in the new workbooks.
        Dim CurWkbook As Workbook
        Dim wkSheet As Worksheet
        Dim newWkbook As Workbook
        Dim wkSheetName As String
        Dim shtcnt(3) As Long
        Dim xpathname As String, dtimestamp As String
        dtimestamp = Format(Now, "yyyymmdd_hhmmss")
        xpathname = "c:\temp\D" & dtimestamp & "\"
        MkDir xpathname
        Set CurWkbook = Application.ActiveWorkbook
    
        shtcnt(2) = ActiveWorkbook.Sheets.Count
        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual
        For Each wkSheet In CurWkbook.Worksheets
          shtcnt(1) = shtcnt(1) + 1
          Application.StatusBar = shtcnt(1) & "/" & shtcnt(2) & _
              "  " & wkSheet.Name
          wkSheetName = Trim(wkSheet.Name)
          If wkSheetName = Left(Application.ActiveWorkbook.Name, _
             Len(Application.ActiveWorkbook.Name) - 4) Then _
             wkSheetName = wkSheetName & "_D" & dtimestamp
          Workbooks.Add
          ActiveWorkbook.SaveAs _
             Filename:=xpathname & wkSheetName & ".xls", _
             FileFormat:=xlNormal, Password:="", _
             WriteResPassword:="", CreateBackup:=False, _
             ReadOnlyRecommended:=False
          Set newWkbook = ActiveWorkbook
          
          Application.DisplayAlerts = False
          newWkbook.Worksheets("sheet1").Delete
          On Error Resume Next
          newWkbook.Worksheets(wkSheet.Name).Delete
          On Error GoTo 0
          Application.DisplayAlerts = True
     
          CurWkbook.Worksheets(wkSheet.Name).Copy Before:=newWkbook.Sheets(1)
          'no duplicate sheet1 because they begin with "a"
          ActiveWorkbook.Save
          ActiveWorkbook.Close
        Next wkSheet
        Application.StatusBar = False      'return control to Excel
        Application.Calculation = xlCalculationAutomatic
        Application.ScreenUpdating = True
    End Sub
    change the xpathname to a diffrent path if you want
    note this will save the two sheets "template" and "download" You may want to manually remove them from the folder.


    Is excel limited on the number of worksheets it contains within one workbook?
    In this case the amount of sheets that you can have in one workbook is only limited to the amount of Ram.
    Actually for 2003 it could be 256, Though im thinking that 2003 is still allowed to max the ram.
    though it seams that either way you are staying under the threashold.

    knowing that this is sample data.
    If the cell that is used for the sheet name contains more that 256 charters it will error as 256, Though i cant see that the cell should contain more than this.
    Last edited by D_Rennie; 10-17-2009 at 01:10 AM.

  11. #11
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    Hello again Dave,

    Thanks again for the time you are taking to help with this! I get that you don't understand why I need this in the way I do, the reason is that I have deleted sensitive information from the sheet. Basically the row that I copy and paste into a new workbook will fill in a spreadsheet below it.

    You bring up a good point though as I will have to add this later. Basically the workbook has two sheets. the sheet named "blank" is the sheet that will recieve the pasted row. Underneath that newly pasted row is a series of rows that will pull from the pasted row. This does not need to be included in the macro because it can be done in excel as a template.

    The entire sheet "blank" will need to be copied into a new workbook and saved as its own original workbook. I do not want the "download" sheet copied into the new workbook, I only want the "blank" sheet in the new workbook.

    As the macro works, it will find that there are duplicate filenames and it will run into an error. If the duplicate file name "Adam" already exists, I'd like the new filename to be "Adam2." If "Adam" and "Adam2" exists, the next would be "Adam3"


    To answer your question about the code you provided last, (which I thought I already answered, so I apologize if I had not) your code gave me the same error as I was getting with my code at the same place. It was however working better than my original code by naming the sheets as I needed in the paragraph above. I couldn't figure out how to manipulate the code to give me the proper results though (due to my limited VBA knowledge).

    I think my previous macro must have been a problem due to the amount of memory in my computer then. It would always stop after about the 58th sheet it created.

    I would like to "add a print command" to the code but first I need to see if the code works right. So if you wouldn't mind putting that in the code with single quotes so I can see it and activate it when I'm ready that would be AWESOME!

    Ok I added the code above to my code and it gives me interesting results. It creates a new folder for each new workbook that it saves, and then in each folder it has created 3 seperate sheets. 1 sheet is titled correctly and is exactly the file that I need but there are two other sheets in the folder named "Sheets2" and "Sheets3" which I don't need. How do I get just the named workbooks to appear in the same folder?

    Also, this extra code is leaving 192 open workbooks when it is finished and it took about 5 minutes to run the macro.

    Is that enough/too much info? let me know.
    Thanks!

    Sub automate_linesheets_2()
    Dim finalrow As Long
    Dim filenum As Long
        finalrow = Sheets("Download").Cells.SpecialCells(xlCellTypeLastCell).Row
        Debug.Print finalrow
        
    Sheets("Download").Select
        Range("C3").Select
        Range(Cells(3, 1), Cells(finalrow, 34)).Sort Key1:=Range("C3"), Order1:=xlDescending, Key2:= _
            Range("D3"), Order2:=xlDescending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, _
            Orientation:=xlTopToBottom, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal
       
    Dim I As Long
        For I = 3 To finalrow
        Workbooks("Linesheet Template revised_20091016_sample.xls").Worksheets("Download").Activate
        Cells(I, 2).Select
            If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
            filenum = 1
               Range(Cells(I, 1), Cells(I, 34)).Copy
               Sheets("Blank").Range("A3").PasteSpecial xlAll
                Sheets("blank").Select
                Cells.Select
                Selection.Copy
                Workbooks.Add
                ActiveSheet.Paste
                With Selection.Interior
                    .ColorIndex = 2
                    .Pattern = xlSolid
                ActiveSheet.Name = Range("C3")
                End With
            End If
      Dim CurWkbook As Workbook
        Dim wkSheet As Worksheet
        Dim newWkbook As Workbook
        Dim wkSheetName As String
        Dim shtcnt(3) As Long
        Dim xpathname As String, dtimestamp As String
        dtimestamp = Format(Now, "yyyymmdd_hhmmss")
        xpathname = "P:\Review\Macro Training\Linesheet Drop Folder" & dtimestamp & "\"
        MkDir xpathname
        Set CurWkbook = Application.ActiveWorkbook
    
        shtcnt(2) = ActiveWorkbook.Sheets.Count
        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual
        For Each wkSheet In CurWkbook.Worksheets
          shtcnt(1) = shtcnt(1) + 1
          Application.StatusBar = shtcnt(1) & "/" & shtcnt(2) & _
              "  " & wkSheet.Name
          wkSheetName = Trim(wkSheet.Name)
          If wkSheetName = Left(Application.ActiveWorkbook.Name, _
             Len(Application.ActiveWorkbook.Name) - 4) Then _
             wkSheetName = wkSheetName & "_D" & dtimestamp
          Workbooks.Add
          ActiveWorkbook.SaveAs _
             FileName:=xpathname & wkSheetName & ".xls", _
             FileFormat:=xlNormal, Password:="", _
             WriteResPassword:="", CreateBackup:=False, _
             ReadOnlyRecommended:=False
          Set newWkbook = ActiveWorkbook
          
          Application.DisplayAlerts = False
          newWkbook.Worksheets("sheet1").Delete
          On Error Resume Next
          newWkbook.Worksheets(wkSheet.Name).Delete
          On Error GoTo 0
          Application.DisplayAlerts = True
     
          CurWkbook.Worksheets(wkSheet.Name).Copy Before:=newWkbook.Sheets(1)
          'no duplicate sheet1 because they begin with "a"
          ActiveWorkbook.Save
          ActiveWorkbook.Close
        Next wkSheet
        Application.StatusBar = False      'return control to Excel
        Application.Calculation = xlCalculationAutomatic
        Application.ScreenUpdating = True
        
        Next I
        
               
    End Sub
    Attached Images Attached Images
    Last edited by curbster; 10-19-2009 at 02:21 PM.

  12. #12
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    Ok do you want a new folder with "Linesheet Drop Folder" & dtimestamp " created for each workbook, That seams even more confising. We can easley get rig of any extra sheets.
    We can just drop all the files into" Linesheet Drop Folder" if you like.

  13. #13
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    No I just want the sheets to save into the Linesheets drop folder as seperate workbooks. That would be great. I would love to eliminate any confusion I can!

    Also, I don't need the time date stamp at all.
    thanks Dave

  14. #14
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    Hello ive redone the code, There is still a bug in there (it errors after a few sheets), I have to go out.
    Sub Creat_Workbook_FromSheetsRows()
    Dim finalrow As Long, filenum As Long, shtExistNum As Long, I As Long
    Dim xpathname As String, wkSheetName As String, newWksheetName As String
    
        Application.DisplayAlerts = False
        Application.ScreenUpdating = False
    
    finalrow = Sheets("Download").Cells.SpecialCells(xlCellTypeLastCell).Row
    For I = 2 To finalrow
        Workbooks(ThisWorkbook.Name).Worksheets("Download").Activate
            If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
                Range(Cells(I, 1), Cells(I, 34)).Copy
                Sheets("Blank").Range("A3").PasteSpecial xlAll
                Sheets("blank").Cells.Copy
                Workbooks.Add
                ActiveSheet.Paste
                    With Selection.Interior
                        .ColorIndex = 2
                        .Pattern = xlSolid
                        ActiveSheet.Name = ActiveSheet.Range("C3")
                    End With
            End If
    
    ActiveWorkbook.Sheets(3).Delete
    ActiveWorkbook.Sheets(2).Delete
    
    xpathname = ThisWorkbook.Path & "\" & "Sheets" & "\"
    If Not FileOrDirExists(xpathname) Then
        MkDir xpathname
    End If
    
        wkSheetName = Trim(ActiveSheet.Name)
        newWksheetName = Trim(ActiveSheet.Name)
        shtExistNum = 1
    
    CheekName:
        If FileOrDirExists(xpathname & newWksheetName & ".xls") Then
                    shtExistNum = shtExistNum + 1
                    newWksheetName = wkSheetName & shtExistNum
                    GoTo CheekName
                Else
                    If newWksheetName = wkSheetName Then newWksheetName = wkSheetName
        End If
    
        ActiveWorkbook.SaveAs Filename:=xpathname & newWksheetName & ".xls", _
        FileFormat:=xlNormal, Password:="", WriteResPassword:="", CreateBackup:=False, _
        ReadOnlyRecommended:=False
        ActiveWorkbook.Close
        
    Next I
        Application.DisplayAlerts = True
        Application.ScreenUpdating = False
    End Sub
    
    Function FileOrDirExists(PathName As String) As Boolean
         
        Dim iTemp As Integer
         
        On Error Resume Next
        iTemp = GetAttr(PathName)
         
        Select Case Err.Number
        Case Is = 0
            FileOrDirExists = True
        Case Else
            FileOrDirExists = False
        End Select
         
        On Error GoTo 0
    End Function
    we will update to the correct folder once everythink is good.

  15. #15
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    after steeping back for a min i see the problem may be in the fileexist loop

  16. #16
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    I didnt carry through on the 1st if statement correctly,
    also added a boolen

    Sub Creat_Workbook_FromSheetsRows()
    Dim finalrow As Long, filenum As Long, shtExistNum As Long, I As Long
    Dim xpathname As String, wkSheetName As String, newWksheetName As String
    
        Application.DisplayAlerts = False
        Application.ScreenUpdating = False
    
    finalrow = Sheets("Download").Cells.SpecialCells(xlCellTypeLastCell).Row
    For I = 2 To finalrow
        Workbooks(ThisWorkbook.Name).Worksheets("Download").Activate
            If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
                Range(Cells(I, 1), Cells(I, 34)).Copy
                Sheets("Blank").Range("A3").PasteSpecial xlAll
                Sheets("blank").Cells.Copy
                Workbooks.Add
                ActiveSheet.Paste
                    With Selection.Interior
                        .ColorIndex = 2
                        .Pattern = xlSolid
                        ActiveSheet.Name = ActiveSheet.Range("C3")
                    End With
            
    
    ActiveWorkbook.Sheets(3).Delete
    ActiveWorkbook.Sheets(2).Delete
    
    xpathname = ThisWorkbook.Path & "\" & "Sheets" & "\"
    If Not FileOrDirExists(xpathname) Then
        MkDir xpathname
    End If
    
        wkSheetName = Trim(ActiveSheet.Name)
        newWksheetName = Trim(ActiveSheet.Name)
        shtExistNum = 1
    Dim lastfile As Boolean
    lastfile = False
    CheekName:
        If FileOrDirExists(xpathname & newWksheetName & ".xls") Then
                    shtExistNum = shtExistNum + 1
                    newWksheetName = wkSheetName & shtExistNum
                    lastfile = True
                    GoTo CheekName
         End If
                    
                    If lastfile = True Then
                            newWksheetName = wkSheetName & shtExistNum
                        Else
                            newWksheetName = wkSheetName
                    End If
    
        ActiveWorkbook.SaveAs Filename:=xpathname & newWksheetName & ".xls", _
        FileFormat:=xlNormal, Password:="", WriteResPassword:="", CreateBackup:=False, _
        ReadOnlyRecommended:=False
        ActiveWorkbook.Close
    End If
    Next I
        Application.DisplayAlerts = True
        Application.ScreenUpdating = False
    End Sub
    
    Function FileOrDirExists(PathName As String) As Boolean
         
        Dim iTemp As Integer
         
        On Error Resume Next
        iTemp = GetAttr(PathName)
         
        Select Case Err.Number
        Case Is = 0
            FileOrDirExists = True
        Case Else
            FileOrDirExists = False
        End Select
         
        On Error GoTo 0
    End Function

  17. #17
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    Dave,
    thanks again for all the help! It looks like we're on the right track now! You mentioned we can save to the "right folder" once we get everything going right so you probably know that it is saving to my applications folder under Excel where everyone's "personal.xls" file is saved.

    I had to change some code ("thisworkbook.name") to the actual file name I had open and I put that name in quotes.

    i.e.
    Workbooks("Linesheet Template revised_20091016_sample.xls").Worksheets("Download")

    I figure I shouldn't have to do that but I could be wrong? Not sure. Once that was changed, the code ran fine. It was considerably slow but to be honest, as long as it runs right and gives me the desired results I'm not going to complain! So thank you for that.

    I don't understand functions yet, so you lost me with that code. No worries, its only a matter of time. Strings still confuse me as well. Any pointers would be great or references I could research that would benefit my understanding would be welcomed!

    Is there any way to add a little to bit to this code? If not, no worries, I can do this portion manually but I'm hoping that when we get bigger sets of data that I can avoid another grueling task. Here is what I would need:

    If the (I) row font is Blue or contains a "P" in column 26, then in the same row, column 27 it will contain a number. I need to search all rows for this number and if this number exists (within column 27) then I need to copy the entire row (this row will have a font color red if that helps). In the "blank" worksheet I'll need to insert this row under the first (I) row that we put there. I need to insert all rows that match column 27 within the same worksheet (new workbook we've created).

    A little history/explanation. P stands for parent. We are talking about loans in banking. So the parent loan is going to be the entire loan amount. Some portions of this loan are sold to other banks but we still keep that information on file. So if when a Parent loan is selected, we need to include all related loans with it. These loans which are sold to other banks will have the same "Parent" loan number attached to them within column 27.

    I hope that makes sense.

    I really appreciate all the help thus far!

  18. #18
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    Yes i guess another loop or find could be used to see if any onther lines have the same number as the parent. Though say a line has been found that is related to the parent would that line still require its own workbook.

    Workbooks("Linesheet Template revised_20091016_sample.xls").Worksheets("Download")
    no thats fine normally the line should be fully qualified or
    thisworkbook.Worksheets("Download")
    i take it you got the workbook going where you wanted. though this is what needed changing for this
    xpathname = ThisWorkbook.Path & "\" & "Sheets" & "\"
    Yeah the time it took to create all the workbooks, cant realy do much about that though try at the top of the code. Application.enableevents = false
    and at the end application.enableevents = true. just out of intrest how long did it take to run.

  19. #19
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    Dave,
    For each parent and its sold parts they (Parent and Sold) will have the same parent number in the parent column. By this column alone one can not decipher between them unless they can see color. The parent loans are always in blue font and the sold loans are always in red font. The column immediately to the left of the parent column labels the types of loans as P for parent and S for sold. So if we combine the two into saying that each parent will probably have some sold parts, we need to combine them onto the new workbook as one loan.

    In short, the parent loan will always start in "A3" (on the "blank" tab before being copied into the new workbook) and any sold loans would insert new rows underneath the "A3" row. So if there were 2 sold loans, the sold loans would have their own rows; "A4" and "A5" respectively. The data would be pushed down as many rows as need be depending on how many participations there are. I have seen up to 10 participations but that is rare. Typically they have 2-4 but the code should work at least up to 10 or more. In the future this number could be greater.

    I found out why the macro created a folder in the personal.xls application file, it was because I was running the macro from my personal.xls spreadsheet. my fault.

    I tried the "enableevents" hint you gave at the end of your reply and it took the same amount of time. The macro went through 203 lines and took 3 min, 21 seconds. I didn't know how long it took so I did it again and timed it.

    Thanks,
    Last edited by curbster; 10-20-2009 at 08:50 PM.

  20. #20
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    contains a "P" in column 26, then in the same row, column 27 it will contain a number.
    can you please upload a new sample file as the one you have in this thread i can only see the letter P in column 30, so im gussing the search is then based on column 31. i would rather use the letters and numbers over the color of the rows. as color can be dirrent to code based on how the color got there "CF" and allows for a greater range of human error.

    we dont need a whole heap of rows fulled in just make sure that the data is in the correct place.

    under 4 min to create a couple humdred workbook IMO isnt bad.
    Last edited by D_Rennie; 10-21-2009 at 12:49 AM.

  21. #21
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    I played with this, To test place a new worksheet in the uploaded workbook call it Test,
    this deals with only the 1st line of data in the workbook, see if the results are as expected.
    Sub Creat_Workbook_FromSheetsRows()
    Dim finalrow As Long, filenum As Long, shtExistNum As Long, I As Long
    Dim xpathname As String, wkSheetName As String, newWksheetName As String
    
        Application.DisplayAlerts = False
        Application.ScreenUpdating = False
    
    finalrow = Sheets("Download").Cells.SpecialCells(xlCellTypeLastCell).Row
    I = 2: ' To 3
        Workbooks(ThisWorkbook.Name).Worksheets("Download").Activate
            If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
                Range(Cells(I, 1), Cells(I, 34)).Copy
                Sheets("Blank").Range("A3").PasteSpecial xlAll
                Sheets("blank").Cells.Copy
                'Workbooks.Add
                Sheets("Test").Range("a1").PasteSpecial (xlAll)
                Sheets("Test").Select
                    Dim y As Long, x As Long
                    With ThisWorkbook.Sheets("Download")
                        If .Cells(I, 30).Value = "P" Or .Cells(I, 30).Value = "p" Then
                            y = .Cells(I, 31).Value
                            For x = 2 To finalrow
                                If x = I Then GoTo samerow
                                If .Cells(x, 31).Value = y Then
                                    .Range(.Cells(x, 1), .Cells(x, 34)).Copy
                                    Cells(Rows.Count, "A").End(xlUp).Offset(1).PasteSpecial (xlAll)
                                End If
    samerow:
                            Next x
                        End If
                    End With
                                
    End If
    
        Application.DisplayAlerts = True
        Application.ScreenUpdating = False
    End Sub
    though i still think i need more accurate data.

  22. #22
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    Dave,
    I am sending a new worksheet with correctly updated columns. Good eye! I hadn't noticed they had a different number of columns.

    I am not clear why you wanted to add a "test" sheet but I did in this attachment I'm sending you. The "Blank" sheet has all the information in it that I need to use as a template so I am a little confused on the logic...

    Also, this code will not allow me to test because it only does the first line (like you mention). In order to give an accurate test result, it would need to do at least 30 lines.

    yeah I'm not complaining about this macro doing the work for me in under 4 min! Believe me I am ECSTATIC!

    What does "IMO" stand for? Also, not sure what "CF" is.

    Thanks
    Attached Files Attached Files

  23. #23
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    i meant to open the workbook that you 1st uploaded and inster a page test to run the last code to see if it had the correct outcome of the 1st line of data.
    anyhow ill put it all together and see what happens.

    Im my opition, Conditional formatting.

  24. #24
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    This should do it
    Option Explicit
    Public glb_origCalculationMode As Integer
    
    Sub Creat_Workbook_FromSheetsRows()
    Dim finalrow As Long, filenum As Long, shtExistNum As Long, I As Long, y As Long, x As Long
    Dim xpathname As String, wkSheetName As String, newWksheetName As String
    Dim lastfile As Boolean
    On Error GoTo ResetSpeed
    SpeedOn
    finalrow = ThisWorkbook.Sheets("Download").Cells.SpecialCells(xlCellTypeLastCell).Row
    For I = 2 To finalrow
        ThisWorkbook.Sheets("Blank").Range("A3:AH1000").Delete
    ThisWorkbook.Sheets("Download").Activate
        'Workbooks(ThisWorkbook.Name).Worksheets("Download").Activate
            If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
                Range(Cells(I, 1), Cells(I, 34)).Copy
                ThisWorkbook.Sheets("Blank").Range("A3").PasteSpecial xlAll
                With ThisWorkbook.Sheets("Download")
                        If .Cells(I, 26).Value = "P" Or .Cells(I, 26).Value = "p" Then
                            If .Cells(I, 27).Value = vbNullString Then GoTo NoMoreRows
                            y = .Cells(I, 27).Value
                            For x = 2 To finalrow
                                If x = I Then GoTo samerow
                                If .Cells(x, 27).Value = y Then
                                    .Range(.Cells(x, 1), .Cells(x, 34)).Copy
                                    Sheets("Blank").Cells(Rows.Count, "A").End(xlUp).Offset(1).PasteSpecial (xlAll)
                                End If
    samerow:
                            Next x
                        End If
    NoMoreRows:
                End With
            ThisWorkbook.Sheets("Blank").Cells.Copy
                Workbooks.Add
                    ActiveSheet.Paste
                        With Selection.Interior
                            .ColorIndex = 2
                            .Pattern = xlSolid
                        End With
            ActiveSheet.Name = ActiveSheet.Range("C3")
                ActiveWorkbook.Sheets(3).Delete
                ActiveWorkbook.Sheets(2).Delete
    xpathname = ThisWorkbook.Path & "\" & "Sheets" & "\"
        If Not FileOrDirExists(xpathname) Then
            MkDir xpathname
        End If
        wkSheetName = Trim(ActiveSheet.Name)
            newWksheetName = Trim(ActiveSheet.Name)
                shtExistNum = 1
    lastfile = False
    CheekName:
        If FileOrDirExists(xpathname & newWksheetName & ".xls") Then
                    shtExistNum = shtExistNum + 1
                    newWksheetName = wkSheetName & shtExistNum
                    lastfile = True
                    GoTo CheekName
         End If
                    If lastfile = True Then
                            newWksheetName = wkSheetName & shtExistNum
                        Else
                            newWksheetName = wkSheetName
                    End If
        ActiveWorkbook.SaveAs Filename:=xpathname & newWksheetName & ".xls", _
        FileFormat:=xlNormal, Password:="", WriteResPassword:="", CreateBackup:=False, _
        ReadOnlyRecommended:=False
        ActiveWorkbook.Close
            End If
    Next I
    ResetSpeed:
    SpeedOff
    End Sub
    
    Function FileOrDirExists(PathName As String) As Boolean
        Dim iTemp As Integer
        On Error Resume Next
        iTemp = GetAttr(PathName)
        Select Case Err.Number
        Case Is = 0
            FileOrDirExists = True
        Case Else
            FileOrDirExists = False
        End Select
        On Error GoTo 0
    End Function
    
    Sub SpeedOn(Optional StatusBarMsg As String = "Running macro...")
        glb_origCalculationMode = Application.Calculation
        With Application
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
            .DisplayAlerts = False
            .Cursor = xlWait
            .StatusBar = StatusBarMsg
            .EnableCancelKey = xlErrorHandler
        End With
    End Sub
     
    Sub SpeedOff()
        With Application
            .Calculation = glb_origCalculationMode
            .ScreenUpdating = True
            .EnableEvents = True
            .DisplayAlerts = True
            .CalculateBeforeSave = True
            .Cursor = xlDefault
            .StatusBar = False
            .EnableCancelKey = xlInterrupt
        End With
    End Sub
    You may have to adjust the part in the red as i put that in there becouse in the dataset there where letters P found in col 27 and no number in the col 28 so i couldnot match it with anythink.

    And rember the output folder will need changing.

    hope this helps.

  25. #25
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    Dave, take a look at the sample sheet when you run this code. I'll upload an updated one with notes in the "blank" tab. After the macro runs, open one of the spreadsheets that has sold parts and see where it is adding the additional lines. I'll attach an example with this reply.

    Thanks again for your help, this is a dousy.
    Attached Files Attached Files

  26. #26
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    How you going bud,

    well i must say ive now has the crap confused out of me.

    from what i understood if col 26 had a P col 27 had the unique number that would match any sold under the parent.

    you cannot rem out this line
        ThisWorkbook.Sheets("Blank").Range("A3:AH1000").Delete
    if you dont want to delete the range use
        ThisWorkbook.Sheets("Blank").Range("A3:AH1000").clearcontents
    If i run the code exaclly how i posted it i end up with a workbook for every line that passes
     If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
    and for every row that contains the parent in col 26 the a workbook for that customer will contain the parent and assocated sold.

    i did notice that in the data set i looks as if the columns have been sorted with column 3 name and column 16 im guessing that this is the payoff date.
    becouse the 1st payoff date falls before the parent loan payoff date. hence the 1st row of data may not be the parent load for that customer. so Adam3 may be the 1st parent loan since 1-2 are aready created.

    try sorting by col 26 and col 3.

    i take it that the two files you posted are the incorrect out comes of not deleting the cells for each time the loop is run. and not the desired outcome of what you want the code to do.

    if this does not help put together a sample file with about 6 rows of data for 3 diffrent people 2 with a partent loan linked to a sold. and the others unique.
    and create a worksheet for each line of data 6 sheets.

    .
    Last edited by D_Rennie; 10-26-2009 at 04:37 PM.

  27. #27
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    Dave,
    Thanks again for your help, I hear you on being newly confused on this! It must be monday!

    from what i understood if col 26 had a P col 27 had the unique number that would match any sold under the parent.
    That is right.

    you cannot rem out this line
    what does "rem" mean?


    ThisWorkbook.Sheets("Blank").Range("A3:AH1000").clearcontents
    I'm confused why you believe I would want to delete this selection? I need A4 through G161 because that is the area where my worksheet autofills as soon as the row of data is added into the "blank" worksheet.


    If i run the code exaclly how i posted it i end up with a workbook for every line that passes
     If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
    This is right for each line. The real set of data will never contain negative numbers in these two columns for any sold parts.


    i did notice that in the data set i looks as if the columns have been sorted with column 3 name and column 16 im guessing that this is the payoff date.
    becouse the 1st payoff date falls before the parent loan payoff date. hence the 1st row of data may not be the parent load for that customer. so Adam3 may be the 1st parent loan since 1-2 are aready created.

    try sorting by col 26 and col 3.
    that works, we can sort by 26 and 3.


    i take it that the two files you posted are the incorrect out comes of not deleting the cells for each time the loop is run. and not the desired outcome of what you want the code to do.
    Yes, the two files I posted were the incorrect files. I guess it will help if I posted how they SHOULD look. I'll do that in this reply.

    if this does not help put together a sample file with about 6 rows of data for 3 diffrent people 2 with a partent loan linked to a sold. and the others unique.
    and create a worksheet for each line of data 6 sheets.
    If I understand right, lets say there is one person with two parent loans and 4 sold parts for each of these 2 parents. In the data sheet ("Download") lets say this one person took up 10 rows when sorted correctly. This person would get only two workbooks because he/she has two parent loans. All we are concerned with are the parent loans but we have to subtract the sold parts (negative numbers as explained above) before we have our own accurate data.

    I really hope that makes sense. its hard to explain without sharing our actual worksheet with the forum, which I believe would be considered "sensitive information" and not kosher.

    Let me know if that doesn't make sense!

    thanks again!

    P.S.~ see the samplesheet01 attached to this reply. Also, as the macro goes through it will need to delete all the red rows before it goes to the next name. Nothing should appear in the grey'ed out area.
    Attached Files Attached Files
    Last edited by curbster; 10-26-2009 at 08:37 PM.

  28. #28
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    ok

    what you need is, You dont want a new workbook for each row that has a S in col26 (easley done when sorted in this manner.)

    What i said about the clear(delete) of the rows on (blank) still stands becouse the template will need to be Reset before it can be used for a new line of data from the download. Else the end display of the data will be incorrect.

    Is there information in below A4 in the original data. if not the clearing the cells shouldnot matter. Though if there is data in or below A4 )formulars whatever) the way i wrote the code it would not have placed the sold lines in the correct place in the 1st place.

    maybe a new row needs to be inserted and only delete the rows that we insert to refresh the sheet.

    that seams fairly simple though i dont want to go through and recode it only to find out that the method of codeing will not work becouse the uploaded data has not been accurate.

    You can post the workbook to DRennie@Dodo.com.au. if you cant send to workbook i guess i can code to what i think needs to happen.

  29. #29
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    try
    Option Explicit
    Public glb_origCalculationMode As Integer
    
    Sub Creat_Workbook_FromSheetsRows()
    Dim finalrow As Long, filenum As Long, shtExistNum As Long, I As Long, y As Long, x As Long
    Dim xpathname As String, wkSheetName As String, newWksheetName As String
    Dim lastfile As Boolean
    On Error GoTo ResetSpeed
    SpeedOn
    With ThisWorkbook.Sheets("Download")
        finalrow = .Cells(.Rows.Count, "A").End(xlUp).Row - 1
    End With
    For I = 2 To finalrow
        With ThisWorkbook.Sheets("Blank")
            For x = 100 To 1 Step -1
                If .Cells(x, 26).Value = "S" Then
                    .Rows(x).Delete Shift:=xlUp
                End If
            Next x
        End With
    ThisWorkbook.Sheets("Download").Activate
        If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
        If Cells(I, 26).Value = "S" Then GoTo sold
                Range(Cells(I, 1), Cells(I, 34)).Copy
                ThisWorkbook.Sheets("Blank").Range("A3").PasteSpecial xlAll
                With ThisWorkbook.Sheets("Download")
                        If .Cells(I, 26).Value = "P" Or .Cells(I, 26).Value = "p" Then
                            If .Cells(I, 27).Value = vbNullString Then GoTo NoMoreRows
                            y = .Cells(I, 27).Value
                            For x = 2 To finalrow
                                If x = I Then GoTo samerow
                                If .Cells(x, 27).Value = y Then
                                    .Range(.Cells(x, 1), .Cells(x, 34)).Copy
                                    Sheets("Blank").Range("A4").Insert Shift:=xlDown
                                End If
    samerow:
                            Next x
                        End If
    NoMoreRows:
                End With
            ThisWorkbook.Sheets("Blank").Cells.Copy
                Workbooks.Add
                    ActiveSheet.Paste
                        With Selection.Interior
                            .ColorIndex = 2
                            .Pattern = xlSolid
                        End With
            ActiveSheet.Name = ActiveSheet.Range("C3")
                ActiveWorkbook.Sheets(3).Delete
                ActiveWorkbook.Sheets(2).Delete
    xpathname = ThisWorkbook.Path & "\" & "Sheets" & "\"
        If Not FileOrDirExists(xpathname) Then
            MkDir xpathname
        End If
        wkSheetName = Trim(ActiveSheet.Name)
            newWksheetName = Trim(ActiveSheet.Name)
                shtExistNum = 1
    lastfile = False
    CheekName:
        If FileOrDirExists(xpathname & newWksheetName & ".xls") Then
                    shtExistNum = shtExistNum + 1
                    newWksheetName = wkSheetName & shtExistNum
                    lastfile = True
                    GoTo CheekName
         End If
                    If lastfile = True Then
                            newWksheetName = wkSheetName & shtExistNum
                        Else
                            newWksheetName = wkSheetName
                    End If
        ActiveWorkbook.SaveAs Filename:=xpathname & newWksheetName & ".xls", _
        FileFormat:=xlNormal, Password:="", WriteResPassword:="", CreateBackup:=False, _
        ReadOnlyRecommended:=False
        ActiveWorkbook.Close
            End If
    sold:
    Next I
    ResetSpeed:
    SpeedOff
    End Sub
    
    Function FileOrDirExists(PathName As String) As Boolean
        Dim iTemp As Integer
        On Error Resume Next
        iTemp = GetAttr(PathName)
        Select Case Err.Number
        Case Is = 0
            FileOrDirExists = True
        Case Else
            FileOrDirExists = False
        End Select
        On Error GoTo 0
    End Function
    
    Sub SpeedOn(Optional StatusBarMsg As String = "Running macro...")
        glb_origCalculationMode = Application.Calculation
        With Application
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
            .DisplayAlerts = False
            .Cursor = xlWait
            .StatusBar = StatusBarMsg
            .EnableCancelKey = xlErrorHandler
        End With
    End Sub
     
    Sub SpeedOff()
        With Application
            .Calculation = glb_origCalculationMode
            .ScreenUpdating = True
            .EnableEvents = True
            .DisplayAlerts = True
            .CalculateBeforeSave = True
            .Cursor = xlDefault
            .StatusBar = False
            .EnableCancelKey = xlInterrupt
        End With
    End Sub

  30. #30
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    rember to sort the fields 1st

  31. #31
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    Dave,
    again, thank you for all your help! I would not have been able to do this without your help! (especially since I still don't understand a portion of how its all tied together. :o)

    I have made some minor adjustments and the code is running as desired now. However, I thought about how you said you need to know everything in advance in order to code properly. See explanation below the code as well.

    Option Explicit
    Public glb_origCalculationMode As Integer
    
    Sub Creat_Workbook_FromSheetsRows()
    Dim finalrow As Long, filenum As Long, shtExistNum As Long, I As Long, y As Long, x As Long
    Dim xpathname As String, wkSheetName As String, newWksheetName As String
    Dim lastfile As Boolean
    On Error GoTo ResetSpeed
    SpeedOn
    With ThisWorkbook.Sheets("Download")
        finalrow = .Cells(.Rows.Count, "A").End(xlUp).Row - 1
    End With
    
    Sheets("Download").Select
        Range("C3").Select
        Range(Cells(3, 1), Cells(finalrow, 34)).Sort Key1:=Range("C3"), Order1:=xlAscending, Key2:= _
            Range("Z3"), Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, _
            Orientation:=xlTopToBottom, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal
            
    For I = 3 To finalrow
       
        With ThisWorkbook.Sheets("Blank")
            For x = 10 To 3 Step -1  'the code below will delete any sold from previous that appear on current worksheet
            Debug.Print x
                If .Cells(x, 26).Value = "S" Or .Cells(x, 26).Value = "C" Then 'if the Part Type column contains an "S" then:
                   .Rows(x).Delete Shift:=xlUp 'delete entire row (Sold Participation)
                End If
            Next x
           
        End With
    ThisWorkbook.Sheets("Download").Activate
        If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
        If Cells(I, 26).Value = "S" Or Cells(I, 26).Value = "C" Then GoTo sold 'sold goes to the next I (basically skipping the code below)
                Range(Cells(I, 1), Cells(I, 34)).Copy
                ThisWorkbook.Sheets("Blank").Range("A3").PasteSpecial xlAll
                With ThisWorkbook.Sheets("Download") 'selects tab named "Download" in current workbook
                        If .Cells(I, 26).Value = "P" Or .Cells(I, 26).Value = "p" Then 'parent loan row
                            If .Cells(I, 4).Value = vbNullString Then GoTo NoMoreRows 'loan # row
                            y = .Cells(I, 4).Value 'loan # row
                            For x = 3 To finalrow 'start at row 3 and do every row until final row
                            Debug.Print x 'in the immediate box below, print what row macro is working on
                                If x = I Then GoTo samerow 'if the row it is working on (x) equals I (parent row), go to "samerow:" below
                                If .Cells(x, 27).Value = y Then 'if column AA and the row it is working on's value is equal to the parent loan #, then:
                                    .Range(.Cells(x, 1), .Cells(x, 34)).Copy 'copy the row it is working on
                                    Sheets("Blank").Range("A4").Insert Shift:=xlDown 'in the blank tab, add a row in place of A4
                                End If
    samerow:
                            Next x
                        End If
    NoMoreRows:
                End With
            ThisWorkbook.Sheets("Blank").Cells.Copy
                Workbooks.Add
                    ActiveSheet.Paste
                        With Selection.Interior
                            .ColorIndex = 2
                            .Pattern = xlSolid
                        End With
            ActiveSheet.Name = ActiveSheet.Range("C3")
                ActiveWorkbook.Sheets(3).Delete 'deletes extra unused worksheets
                ActiveWorkbook.Sheets(2).Delete
    xpathname = ThisWorkbook.Path & "\" & "Sheets" & "\" 'adds a folder called "Sheets" wherever the template in which the code is run has been saved.
        If Not FileOrDirExists(xpathname) Then 'if the file name does not exist
            MkDir xpathname 'name file normally
        End If
        wkSheetName = Trim(ActiveSheet.Name)
            newWksheetName = Trim(ActiveSheet.Name)
                shtExistNum = 1
    lastfile = False
    CheekName:
        If FileOrDirExists(xpathname & newWksheetName & ".xls") Then
                    shtExistNum = shtExistNum + 1
                    newWksheetName = wkSheetName & shtExistNum
                    lastfile = True
                    GoTo CheekName
         End If
                    If lastfile = True Then
                            newWksheetName = wkSheetName & shtExistNum
                        Else
                            newWksheetName = wkSheetName
                    End If
        ActiveWorkbook.SaveAs FileName:=xpathname & newWksheetName & ".xls", _
        FileFormat:=xlNormal, Password:="", WriteResPassword:="", CreateBackup:=False, _
        ReadOnlyRecommended:=False
     
        ActiveWorkbook.Close
            End If
    sold:
    
    Next I
    ResetSpeed:
    SpeedOff
    End Sub
    
    Function FileOrDirExists(PathName As String) As Boolean
        Dim iTemp As Integer
        On Error Resume Next
        iTemp = GetAttr(PathName)
        Select Case Err.Number
        Case Is = 0
            FileOrDirExists = True
        Case Else
            FileOrDirExists = False
        End Select
        On Error GoTo 0
    End Function
    
    Sub SpeedOn(Optional StatusBarMsg As String = "Running macro...")
        glb_origCalculationMode = Application.Calculation
        With Application
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
            .DisplayAlerts = False
            .Cursor = xlWait
            .StatusBar = StatusBarMsg
            .EnableCancelKey = xlErrorHandler
        End With
    End Sub
     
    Sub SpeedOff()
        With Application
            .Calculation = glb_origCalculationMode
            .ScreenUpdating = True
            .EnableEvents = True
            .DisplayAlerts = True
            .CalculateBeforeSave = True
            .Cursor = xlDefault
            .StatusBar = False
            .EnableCancelKey = xlInterrupt
        End With
    End Sub

    There is one thing that this code doesn't do, I thought I would be able to just "add this part later" (famous last words of a procrastinater) but the way the code is written it will not recognize formulas when I insert/delete rows. In the "blank" worksheet, lines A72 - A74 would auto populate the sold loan # and in B72 - B74 the current balance. This is the formula I thought I could add there:
     =IF($AA$4>=0,$C$4,"") it will automatically change to =IF($AA$5>=0,$C$5,"") if I insert a row.
    The only solution I can think of is to create an extra 10 blank rows within the "blank" tab right under C3. Then the macro, instead of running its course by deleting one by one, can sweep the 10 rows and go to the next "Download" sheet's row. This might even save a bit of time, but probably un noticable.

    Thoughts? Will this work or do you have a better idea?

    thanks!

  32. #32
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    glad to hear that very think is ending up in tht correct workbook.
    this will protect the sheet layout
    Option Explicit
    Public glb_origCalculationMode As Integer
    
    Sub Creat_Workbook_FromSheetsRows()
    Dim finalrow As Long, filenum As Long, shtExistNum As Long, I As Long, y As Long, x As Long
    Dim xpathname As String, wkSheetName As String, newWksheetName As String
    Dim lastfile As Boolean
    On Error GoTo ResetSpeed
    SpeedOn
    With ThisWorkbook.Sheets("Download")
        finalrow = .Cells(.Rows.Count, "A").End(xlUp).Row - 1
    End With
    
    Sheets("Download").Select
        Range("C3").Select
        Range(Cells(3, 1), Cells(finalrow, 34)).Sort Key1:=Range("C3"), Order1:=xlAscending, Key2:= _
            Range("Z3"), Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, _
            Orientation:=xlTopToBottom, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal
            
    For I = 3 To finalrow
       
        With ThisWorkbook.Sheets("Blank")
            For x = 10 To 3 Step -1  'the code below will delete any sold from previous that appear on current worksheet
            Debug.Print x
                If .Cells(x, 26).Value = "S" Or .Cells(x, 26).Value = "C" Then 'if the Part Type column contains an "S" then:
                   .Rows(x).Delete Shift:=xlUp 'delete entire row (Sold Participation)
                End If
            Next x
           
        End With
    ThisWorkbook.Sheets("Download").Activate
        If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
        If Cells(I, 26).Value = "S" Or Cells(I, 26).Value = "C" Then GoTo sold 'sold goes to the next I (basically skipping the code below)
                Range(Cells(I, 1), Cells(I, 34)).Copy
                ThisWorkbook.Sheets("Blank").Range("A3").PasteSpecial xlAll
                With ThisWorkbook.Sheets("Download") 'selects tab named "Download" in current workbook
                        If .Cells(I, 26).Value = "P" Or .Cells(I, 26).Value = "p" Then 'parent loan row
                            If .Cells(I, 4).Value = vbNullString Then GoTo NoMoreRows 'loan # row
                            y = .Cells(I, 4).Value 'loan # row
                            For x = 3 To finalrow 'start at row 3 and do every row until final row
                            Debug.Print x 'in the immediate box below, print what row macro is working on
                                If x = I Then GoTo samerow 'if the row it is working on (x) equals I (parent row), go to "samerow:" below
                                If .Cells(x, 27).Value = y Then 'if column AA and the row it is working on's value is equal to the parent loan #, then:
                                    .Range(.Cells(x, 1), .Cells(x, 34)).Copy 'copy the row it is working on
                                    Sheets("Blank").Range("A4").Insert Shift:=xlDown 'in the blank tab, add a row in place of A4
                                End If
    samerow:
                            Next x
                        End If
    NoMoreRows:
                End With
            ThisWorkbook.Sheets("Blank").Cells.Copy
                Workbooks.Add
                    ActiveSheet.Cells(1, 1).PasteSpecial (xlAll)
                        'With Selection.Interior
                        '    .ColorIndex = 2
                       '     .Pattern = xlSolid
                      '  End With
            ActiveSheet.Name = ActiveSheet.Range("C3")
                ActiveWorkbook.Sheets(3).Delete 'deletes extra unused worksheets
                ActiveWorkbook.Sheets(2).Delete
    xpathname = ThisWorkbook.Path & "\" & "Sheets" & "\" 'adds a folder called "Sheets" wherever the template in which the code is run has been saved.
        If Not FileOrDirExists(xpathname) Then 'if the file name does not exist
            MkDir xpathname 'name file normally
        End If
        wkSheetName = Trim(ActiveSheet.Name)
            newWksheetName = Trim(ActiveSheet.Name)
                shtExistNum = 1
    lastfile = False
    CheekName:
        If FileOrDirExists(xpathname & newWksheetName & ".xls") Then
                    shtExistNum = shtExistNum + 1
                    newWksheetName = wkSheetName & shtExistNum
                    lastfile = True
                    GoTo CheekName
         End If
                    If lastfile = True Then
                            newWksheetName = wkSheetName & shtExistNum
                        Else
                            newWksheetName = wkSheetName
                    End If
        ActiveWorkbook.SaveAs Filename:=xpathname & newWksheetName & ".xls", _
        FileFormat:=xlNormal, Password:="", WriteResPassword:="", CreateBackup:=False, _
        ReadOnlyRecommended:=False
     
        ActiveWorkbook.Close
            End If
    sold:
    
    Next I
    ResetSpeed:
    SpeedOff
    End Sub
    
    Function FileOrDirExists(PathName As String) As Boolean
        Dim iTemp As Integer
        On Error Resume Next
        iTemp = GetAttr(PathName)
        Select Case Err.Number
        Case Is = 0
            FileOrDirExists = True
        Case Else
            FileOrDirExists = False
        End Select
        On Error GoTo 0
    End Function
    
    Sub SpeedOn(Optional StatusBarMsg As String = "Running macro...")
        glb_origCalculationMode = Application.Calculation
        With Application
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
            .DisplayAlerts = False
            .Cursor = xlWait
            .StatusBar = StatusBarMsg
            .EnableCancelKey = xlErrorHandler
        End With
    End Sub
     
    Sub SpeedOff()
        With Application
            .Calculation = glb_origCalculationMode
            .ScreenUpdating = True
            .EnableEvents = True
            .DisplayAlerts = True
            .CalculateBeforeSave = True
            .Cursor = xlDefault
            .StatusBar = False
            .EnableCancelKey = xlInterrupt
        End With
    End Sub
    the referencing formulars you could add the 10 odd rows and clear their contents.
    Though it seams at 1st look that the formulars could be added in the correct loaction for each line of data at the time of inputing that data line.
    This should allow for the amount of rows needed below A72 to expand with the new line count. this way you would not have to have 10 lines in this section as well.

    also i think you are referencing the incorrect cells in
    =IF($AA$4>=0,$C$4,"") it will automatically change to =IF($AA$5>=0,$C$5,"") if I insert a row.
    Let me have a think about it for a while.

  33. #33
    Registered User
    Join Date
    08-11-2009
    Location
    Gilbert, Arizona, USA
    MS-Off Ver
    Excel 2003
    Posts
    82

    Re: error message when Automating copy/paste worksheets

    here is what I have with the new idea so far:

    Option Explicit
    Public glb_origCalculationMode As Integer
    
    Sub Creat_Workbook_FromSheetsRows()
    Dim finalrow As Long, filenum As Long, shtExistNum As Long, I As Long, y As Long, x As Long
    Dim xpathname As String, wkSheetName As String, newWksheetName As String
    Dim lastfile As Boolean
    On Error GoTo ResetSpeed
    SpeedOn
    With ThisWorkbook.Sheets("Download")
        finalrow = .Cells(.Rows.Count, "A").End(xlUp).Row - 1
    End With
    
    Sheets("Download").Select
        Range("C3").Select
        Range(Cells(3, 1), Cells(finalrow, 34)).Sort Key1:=Range("C3"), Order1:=xlAscending, Key2:= _
            Range("Z3"), Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, _
            Orientation:=xlTopToBottom, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal
            
    For I = 3 To finalrow
        Sheets("Blank").Select
        Range("A3:AH10").clearcontents
           
     
    ThisWorkbook.Sheets("Download").Activate
        If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
        If Cells(I, 26).Value = "S" Or Cells(I, 26).Value = "C" Then GoTo sold 'sold goes to the next I (basically skipping the code below)
                Range(Cells(I, 1), Cells(I, 34)).Copy
                ThisWorkbook.Sheets("Blank").Range("A3").PasteSpecial xlAll
                With ThisWorkbook.Sheets("Download") 'selects tab named "Download" in current workbook
                        If .Cells(I, 26).Value = "P" Or .Cells(I, 26).Value = "p" Then 'parent loan row
                            If .Cells(I, 4).Value = vbNullString Then GoTo NoMoreRows 'loan # row
                            y = .Cells(I, 4).Value 'loan # row
                            For x = 3 To finalrow 'start at row 3 and do every row until final row
                            Debug.Print x 'in the immediate box below, print what row macro is working on
                                If x = I Then GoTo samerow 'if the row it is working on (x) equals I (parent row), go to "samerow:" below
                                If .Cells(x, 27).Value = y Then 'if column AA and the row it is working on's value is equal to the parent loan #, then:
                                    .Range(.Cells(x, 1), .Cells(x, 34)).Copy 'copy the row it is working on
                                    Sheets("Blank").Range("A4").Insert Shift:=xlDown 'in the blank tab, add a row in place of A4
                                End If
    samerow:
                            Next x
                        End If
    NoMoreRows:
                End With
            ThisWorkbook.Sheets("Blank").Cells.Copy
                Workbooks.Add
                    ActiveSheet.Paste
                        With Selection.Interior
                            .ColorIndex = 2
                            .Pattern = xlSolid
                        End With
            ActiveSheet.Name = ActiveSheet.Range("C3")
                ActiveWorkbook.Sheets(3).Delete 'deletes extra unused worksheets
                ActiveWorkbook.Sheets(2).Delete
    xpathname = ThisWorkbook.Path & "\" & "Sheets" & "\" 'adds a folder called "Sheets" wherever the template in which the code is run has been saved.
        If Not FileOrDirExists(xpathname) Then 'if the file name does not exist
            MkDir xpathname 'name file normally
        End If
        wkSheetName = Trim(ActiveSheet.Name)
            newWksheetName = Trim(ActiveSheet.Name)
                shtExistNum = 1
    lastfile = False
    CheekName:
        If FileOrDirExists(xpathname & newWksheetName & ".xls") Then
                    shtExistNum = shtExistNum + 1
                    newWksheetName = wkSheetName & shtExistNum
                    lastfile = True
                    GoTo CheekName
         End If
                    If lastfile = True Then
                            newWksheetName = wkSheetName & shtExistNum
                        Else
                            newWksheetName = wkSheetName
                    End If
           
            For x = 85 To 80 Step -1  'the code below will delete any sold from previous that appear on current worksheet
            Debug.Print x
                If Cells(x, 2).Value = "0" Then 'if the balance is blank then:
                   Rows(x).Delete Shift:=xlUp 'delete entire row (Sold Participation)
                End If
            Next x
           
    
            For x = 10 To 4 Step -1  'the code below will delete any sold from previous that appear on current worksheet
            Debug.Print x
                If Cells(x, 2).Value = "" Then 'if the balance is blank then:
                Debug.Print Cells(x, 2).Value
                   Rows(x).Delete Shift:=xlUp 'delete entire row (Sold Participation)
                End If
            Next x
            
            
                    
                    
        ActiveWorkbook.SaveAs FileName:=xpathname & newWksheetName & ".xls", _
        FileFormat:=xlNormal, Password:="", WriteResPassword:="", CreateBackup:=False, _
        ReadOnlyRecommended:=False
     
        ActiveWorkbook.Close
            End If
    sold:
    
    Next I
    ResetSpeed:
    SpeedOff
    End Sub
    
    Function FileOrDirExists(PathName As String) As Boolean
        Dim iTemp As Integer
        On Error Resume Next
        iTemp = GetAttr(PathName)
        Select Case Err.Number
        Case Is = 0
            FileOrDirExists = True
        Case Else
            FileOrDirExists = False
        End Select
        On Error GoTo 0
    End Function
    
    Sub SpeedOn(Optional StatusBarMsg As String = "Running macro...")
        glb_origCalculationMode = Application.Calculation
        With Application
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
            .DisplayAlerts = False
            .Cursor = xlWait
            .StatusBar = StatusBarMsg
            .EnableCancelKey = xlErrorHandler
        End With
    End Sub
     
    Sub SpeedOff()
        With Application
            .Calculation = glb_origCalculationMode
            .ScreenUpdating = True
            .EnableEvents = True
            .DisplayAlerts = True
            .CalculateBeforeSave = True
            .Cursor = xlDefault
            .StatusBar = False
            .EnableCancelKey = xlInterrupt
        End With
    End Sub
    the only problem is that it does not do the sold parts correctly. I've left empty rows within the template rows 3 - 10 will be input areas (lines copied from "download" worksheet) and rows 80 - 87 will be the Loan # and Balance on the worksheet I sent you.

    I'm leaving work now, looks like you're about 17 hours ahead of my time (USA, Arizona). I'll be back in about 14 hours from now.

    thanks again Dave.

  34. #34
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    yeah no probs i understand what needs to happen here though the only thing that worries me is only allowing 7 lines. something will be worked out.

    Ill post the workbbok to your email.

  35. #35
    Valued Forum Contributor
    Join Date
    05-14-2009
    Location
    gold coast
    MS-Off Ver
    Excel 2007
    Posts
    843

    Re: error message when Automating copy/paste worksheets

    The original question has been solved as have the amendments.

    Curbster/ Workbook in your email.

    Option Explicit
    Public glb_origCalculationMode As Integer
    
    Sub Creat_Workbook_FromSheetsRows()
    Dim finalrow As Long, filenum As Long, shtExistNum As Long, I As Long, y As Long, x As Long
    Dim xpathname As String, wkSheetName As String, newWksheetName As String
    Dim lastfile As Boolean
    On Error GoTo ResetSpeed
    SpeedOn
    With ThisWorkbook.Sheets("Download")
        finalrow = .Cells(.Rows.Count, "A").End(xlUp).Row - 1
    End With
    
    Sheets("Download").Select
        Range("C3").Select
        Range(Cells(3, 1), Cells(finalrow, 34)).Sort Key1:=Range("C3"), Order1:=xlAscending, Key2:= _
            Range("Z3"), Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, _
            Orientation:=xlTopToBottom, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal
            
    For I = 3 To finalrow
        Sheets("Blank").Range("A3:AH16").ClearContents
           
     
    ThisWorkbook.Sheets("Download").Activate
        If Cells(I, 11).Value >= 0 And Cells(I, 12).Value >= 0 Then
        'If Cells(I, 26).Value = "S" Or Cells(I, 26).Value = "C" Then GoTo sold 'sold goes to the next I (basically skipping the code below)
                Range(Cells(I, 1), Cells(I, 34)).Copy
                ThisWorkbook.Sheets("Blank").Range("A3").PasteSpecial xlAll
                
                With ThisWorkbook.Sheets("Download") 'selects tab named "Download" in current workbook
                        If .Cells(I, 26).Value = "P" Or .Cells(I, 26).Value = "p" Then 'parent loan row
                            If .Cells(I, 4).Value = vbNullString Then GoTo NoMoreRows 'loan # row
                            y = .Cells(I, 27).Value 'stop breaking the code y = i if same row i = col27 as this is what you told me where to look from the code was writtem from here
                            For x = 3 To finalrow 'start at row 3 and do every row until final row
    
    
                                If x = I Then GoTo samerow 'if the row it is working on (x) equals I (parent row), go to "samerow:" below
                                If .Cells(x, 27).Value = y Then 'if column AA and the row it is working on's value is equal to the parent loan #, then:
                                    .Range(.Cells(x, 1), .Cells(x, 34)).Copy 'copy the row it is working on
                                    
                                    Sheets("Blank").Range("A1").End(xlDown).Offset(1).PasteSpecial (xlAll) 'in the blank tab, add a row in place of A4
                                End If
    samerow:
                            Next x
                        End If
    NoMoreRows:
                End With
            ThisWorkbook.Sheets("Blank").Cells.Copy
                Workbooks.Add
                    ActiveSheet.Range("A1").PasteSpecial (xlAll)
            ActiveSheet.Name = ActiveSheet.Range("C3")
                ActiveWorkbook.Sheets(3).Delete 'deletes extra unused worksheets
                ActiveWorkbook.Sheets(2).Delete
    xpathname = ThisWorkbook.Path & "\" & "Sheets" & "\" 'adds a folder called "Sheets" wherever the template in which the code is run has been saved.
        If Not FileOrDirExists(xpathname) Then 'if the file name does not exist
            MkDir xpathname 'name file normally
        End If
        wkSheetName = Trim(ActiveSheet.Name)
            newWksheetName = Trim(ActiveSheet.Name)
                shtExistNum = 1
    lastfile = False
    CheekName:
        If FileOrDirExists(xpathname & newWksheetName & ".xls") Then
                    shtExistNum = shtExistNum + 1
                    newWksheetName = wkSheetName & shtExistNum
                    lastfile = True
                    GoTo CheekName
         End If
                    If lastfile = True Then
                            newWksheetName = wkSheetName & shtExistNum
                        Else
                            newWksheetName = wkSheetName
                    End If
           
            For x = 95 To 83 Step -1  'the code below will delete any sold from previous that appear on current worksheet
            Debug.Print x
                If Cells(x, 2).Value = "0" Then 'if the balance is blank then:
                   Rows(x).Delete Shift:=xlUp 'delete entire row (Sold Participation)
                End If
            Next x
           
    
            For x = 15 To 4 Step -1  'the code below will delete any sold from previous that appear on current worksheet
                If Cells(x, 2).Value = "" Then 'if the balance is blank then:
                Debug.Print Cells(x, 2).Value
                   Rows(x).Delete Shift:=xlUp 'delete entire row (Sold Participation)
                End If
            Next x
            
            
                    
                    
        ActiveWorkbook.SaveAs Filename:=xpathname & newWksheetName & ".xls", _
        FileFormat:=xlNormal, Password:="", WriteResPassword:="", CreateBackup:=False, _
        ReadOnlyRecommended:=False
     
        ActiveWorkbook.Close
            End If
    sold:
    
    Next I
    ResetSpeed:
    SpeedOff
    End Sub
    
    Function FileOrDirExists(PathName As String) As Boolean
        Dim iTemp As Integer
        On Error Resume Next
        iTemp = GetAttr(PathName)
        Select Case Err.Number
        Case Is = 0
            FileOrDirExists = True
        Case Else
            FileOrDirExists = False
        End Select
        On Error GoTo 0
    End Function
    
    Sub SpeedOn(Optional StatusBarMsg As String = "Running macro...")
        glb_origCalculationMode = Application.Calculation
        With Application
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
            .DisplayAlerts = False
            .Cursor = xlWait
            .StatusBar = StatusBarMsg
            .EnableCancelKey = xlErrorHandler
        End With
    End Sub
     
    Sub SpeedOff()
        With Application
            .Calculation = glb_origCalculationMode
            .ScreenUpdating = True
            .EnableEvents = True
            .DisplayAlerts = True
            .CalculateBeforeSave = True
            .Cursor = xlDefault
            .StatusBar = False
            .EnableCancelKey = xlInterrupt
        End With
    End Sub
    Thankyou

  36. #36
    Forum Expert
    Join Date
    01-03-2006
    Location
    Waikato, New Zealand
    MS-Off Ver
    2010 @ work & 2007 @ home
    Posts
    2,243

    Re: error message when Automating copy/paste worksheets

    hi all,

    Dave, good perseverance to provide the solution here

    I've glanced at the full thread but haven't paid close attention to the details & thought I may add my 2 cents worth - for what it's worth...

    I have modified your code from post " 35 slightly by using more With statements to group references to/actions on the same object and tried to prefix my changes with triple hash comments ("'###...").
    This code may not be noticeably faster at all (I haven't tested it for speed or correctness) - but it may be if there are enough workbooks being created.

    The next "big" speed increase that I can think of would be to pull the relevant ranges into memory (arrays), process them in memory & then perform the actions on the sheet. This is because each time information is drawn from the spreadsheet there is a cumulative performance impact.

    Option Explicit
    Public glb_origCalculationMode As Integer
    Public glb_OrigNumberOfShtsInNewFile As Long
    
    Sub Creat_Workbook_FromSheetsRows()
    Dim finalrow As Long, filenum As Long, shtExistNum As Long, I As Long, y As Long, x As Long
    Dim xpathname As String, wkSheetName As String, newWksheetName As String
    Dim lastfile As Boolean
    Dim DwnloadSht As Worksheet
    Dim BlankSht As Worksheet
    Dim NewWB As Workbook
    Dim NewWS As Worksheet
    
        On Error GoTo ResetSpeed
        SpeedOn
        Set DwnloadSht = ThisWorkbook.Sheets("Download")
        Set BlankSht = ThisWorkbook.Sheets("Blank")
        With DwnloadSht
            finalrow = .Cells(.Rows.Count, "A").End(xlUp).Row - 1
            Application.got .Range("C3")    '.Select
            .Range(.Cells(3, 1), .Cells(finalrow, 34)).Sort Key1:=.Range("C3"), Order1:=xlAscending, Key2:= _
                                                            .Range("Z3"), Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, _
                                                            Orientation:=xlTopToBottom, DataOption1:=xlSortNormal, DataOption2:=xlSortNormal
        End With
    
        For I = 3 To finalrow
            BlankSht.Range("A3:AH16").ClearContents    '### does this need to be inside the loop?
            With DwnloadSht
                '### not needed            .Activate
                If .Cells(I, 11).Value >= 0 And .Cells(I, 12).Value >= 0 Then
                    'If Cells(I, 26).Value = "S" Or Cells(I, 26).Value = "C" Then GoTo sold 'sold goes to the next I (basically skipping the code below)
                    .Range(.Cells(I, 1), .Cells(I, 34)).Copy BlankSht.Range("A3")
                    'selects tab named "Download" in current workbook
                    If UCase(.Cells(I, 26).Value) = "P" Then     'parent loan row
                        If .Cells(I, 4).Value = vbNullString Then GoTo NoMoreRows    'loan # row
                        y = .Cells(I, 27).Value    'stop breaking the code y = i if same row i = col27 as this is what you told me where to look from the code was writtem from here
                        For x = 3 To finalrow    'start at row 3 and do every row until final row
                            If x = I Then GoTo samerow    'if the row it is working on (x) equals I (parent row), go to "samerow:" below
                            If .Cells(x, 27).Value = y Then    'if column AA and the row it is working on's value is equal to the parent loan #, then:
                                '### lines merged - copy the row it is working on, into 'the blank tab, add a row in place of A4
                                .Range(.Cells(x, 1), .Cells(x, 34)).Copy BlankSht.Range("A1").End(xlDown).Offset(1)
                            End If
    samerow:
                        Next x
                    End If
    NoMoreRows:
                    xpathname = ThisWorkbook.Path & "\" & "Sheets" & "\"    'adds a folder called "Sheets" wherever the template in which the code is run has been saved.
                    If Not FileOrDirExists(xpathname) Then    'if the file name does not exist
                        MkDir xpathname    'name file normally
                    End If
    
                    Set NewWB = Workbooks.Add
                    '### not necessary due to addition in the SpeedOn/SpeedOff macros
                    'With NewWB
                    '                .Sheets(3).Delete    'deletes extra unused worksheets
                    '                .Sheets(2).Delete
                    'End With
                    Set NewWS = ActiveSheet
                    With NewWS
                        '### limit this to the used range
                        BlankSht.Cells.Copy .Range("A1")
                        .Name = .Range("C3")
                        wkSheetName = Trim(.Name)
                        newWksheetName = Trim(.Name)
                        shtExistNum = 1
                        lastfile = False
    CheekName:
                        If FileOrDirExists(xpathname & newWksheetName & ".xls") Then
                            shtExistNum = shtExistNum + 1
                            newWksheetName = wkSheetName & shtExistNum
                            lastfile = True
                            GoTo CheekName
                        End If
                        If lastfile = True Then
                            newWksheetName = wkSheetName & shtExistNum
                        Else
                            newWksheetName = wkSheetName
                        End If
    
                        '### it  would be possible to change (both of the following loops) to an array & range for delteion built in memory to prevent repeated calls to the worksheet
                        For x = 95 To 83 Step -1  'the code below will delete any sold from previous that appear on current worksheet
                            '###not needed after testing                   Debug.Print x
                            If .Cells(x, 2).Value = "0" Then    'if the balance is blank then:
                                .Rows(x).Delete Shift:=xlUp    'delete entire row (Sold Participation)
                            End If
                        Next x
    
                        For x = 15 To 4 Step -1  'the code below will delete any sold from previous that appear on current worksheet
                            If .Cells(x, 2).Value = "" Then    'if the balance is blank then:
                                '###not needed after testing                        Debug.Print Cells(x, 2).Value
                                .Rows(x).Delete Shift:=xlUp    'delete entire row (Sold Participation)
                            End If
                        Next x
                    End With
    
                    With NewWB
                        .SaveAs Filename:=xpathname & newWksheetName & ".xls", _
                                FileFormat:=xlNormal, Password:="", WriteResPassword:="", CreateBackup:=False, _
                                ReadOnlyRecommended:=False
                        .Close
                    End With
                    Set NewWS = Nothing
                    Set NewWB = Nothing
                End If
            End With
    sold:
        Next I
    ResetSpeed:
        Set DwnloadSht = Nothing
        Set BlankSht = Nothing
        SpeedOff
    End Sub
    
    Function FileOrDirExists(PathName As String) As Boolean
    Dim iTemp As Integer
        On Error Resume Next
        iTemp = GetAttr(PathName)
        Select Case Err.Number
            Case Is = 0
                FileOrDirExists = True
            Case Else
                FileOrDirExists = False
        End Select
        On Error GoTo 0
    End Function
    
    Sub SpeedOn(Optional StatusBarMsg As String = "Running macro...")
        With Application
            glb_origCalculationMode = .Calculation
            glb_OrigNumberOfShtsInNewFile = .SheetsInNewWorkbook    '### added
            .SheetsInNewWorkbook = 1    '### added
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
            .DisplayAlerts = False
            .Cursor = xlWait
            .StatusBar = StatusBarMsg
            .EnableCancelKey = xlErrorHandler
        End With
    End Sub
    
    Sub SpeedOff()
        With Application
            .Calculation = glb_origCalculationMode
            .SheetsInNewWorkbook = glb_OrigNumberOfShtsInNewFile    '### added
            .EnableEvents = True
            .DisplayAlerts = True
            .CalculateBeforeSave = True
            .Cursor = xlDefault
            .StatusBar = False
            .EnableCancelKey = xlInterrupt
            .ScreenUpdating = True    '### moved to the last action
        End With
    End Sub
    hth
    Rob
    Rob Brockett
    Kiwi in the UK
    Always learning & the best way to learn is to experience...

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1