Excel vba copy method failed

  • #2

Not sure why it fails.
Maybe you can try this:
1. Add Debug.Print

VBA Code:

Debug.Print txtClaimsFname
Debug.Print txtClaimsShtName
Debug.Print txtMacroFname
Workbooks(txtClaimsFname).Worksheets(txtClaimsShtName).Copy After:=Workbooks(txtMacroFname).Worksheets("By Market Report")

2. Do the copy manually & record the process by Macro recorder. Maybe you can see something different with the names there.

Fluff

Fluff

MrExcel MVP, Moderator


  • #3

Do either of the workbooks, have workbook protection set on the Review tab?
Does the macro workbook already have a sheet with the same names as the sheet you are trying to copy?

  • #4

Not sure why it fails.
Maybe you can try this:
1. Add Debug.Print

VBA Code:

Debug.Print txtClaimsFname
Debug.Print txtClaimsShtName
Debug.Print txtMacroFname
Workbooks(txtClaimsFname).Worksheets(txtClaimsShtName).Copy After:=Workbooks(txtMacroFname).Worksheets("By Market Report")

2. Do the copy manually & record the process by Macro recorder. Maybe you can see something different with the names there.

Thank you, Akuini. I have been including debug.print on these variables ahead of the copy code, and the content matches what is displayed when I step through the code and hover over the variables. Thanks for the macro recorder idea. Unfortunately, I tried these combinations; the code chokes at line 2, whether it is an activate or select:

Macro recorder code:
Windows(«Interim v1.2 test claims.xlsx»). Activate
Sheets(«Provider Disruption Report»).Select
Sheets(«Provider Disruption Report»).Copy Before:=Workbooks( _
«VBA DA Template 1.2. adding geo code.xlsm»).Sheets(3)
Windows(«Interim v1.2 test claims.xlsx»). Activate
Sheets(«Geocoded»).Select
Sheets(«Geocoded»).Copy Before:=Workbooks( _
«VBA DA Template 1.2. adding geo code.xlsm»).Sheets(4)

I tried dropping the macro recorder code into my code, and it bombed. That tells me something needs to be edited.

‘The following code causes error: select method of worksheet class failed at line 2,
Windows(txtClaimsFname).Activate
Sheets(txtClaimsShtName).Select
Sheets(txtClaimsShtName).Copy Before:=Workbooks(txtMacroFname).Sheets(3)
Windows(txtClaimsFname).Activate
Sheets(txtGeoClaimsShtName).Select
Sheets(txtGeoClaimsShtName).Copy Before:=Workbooks(txtMacroFname).Sheets(4)

‘Here, I specified the workbook name. Error message: select method of worksheet class failed at Line 2.
Windows(txtClaimsFname).Activate
‘Workbooks(txtClaimsFname).Sheets(txtClaimsShtName).Select
‘Workbooks(txtClaimsFname).Sheets(txtClaimsShtName).Copy Before:=Workbooks(txtMacroFname).Sheets(3)
‘Workbooks(txtClaimsFname).Activate
‘Workbooks(txtClaimsFname).Sheets(«Geocoded»).Select
‘Workbooks(txtClaimsFname).Sheets(«Geocoded»).Copy Before:=Workbooks(txtMacroFname).Sheets(4)

‘ I tried to copy both worksheets. This code creates error message: activate method of worksheet class failed at line 2:
Windows(txtClaimsFname).Activate
Sheets(txtClaimsShtName).Activate
Sheets(Array(txtClaimsShtName, txtGeoClaimsShtName)).Select
Sheets(txtGeoClaimsShtName).Activate
Sheets(Array(txtClaimsShtName, txtGeoClaimsShtName)).Copy Before:=Workbooks(txtMacroFname).Sheets(3)

What is the better way to code this?

  • #5

Do either of the workbooks, have workbook protection set on the Review tab?
Does the macro workbook already have a sheet with the same names as the sheet you are trying to copy?

Hello, Fluff: there is no workbook protection in place in either file. The macro file and the claims file do not share worksheet or worksheet names until the copy code runs.

  • #6

Unfortunately, I tried these combinations; the code chokes at line 2,

It’s weird.
Is it possible that you have trailing space in txtClaimsShtName?
Try this:

VBA Code:

Debug.Print txtClaimsShtName = Trim(txtClaimsShtName)
Debug.Print "Provider Disruption Report" = txtClaimsShtName
Workbooks(txtClaimsFname).Worksheets(txtClaimsShtName).Copy After:=Workbooks(txtMacroFname).Worksheets("By Market Report")

If Debug.Print result is False then there’s your answer.

Last edited: Aug 31, 2021

  • #7

Akuini: Thanks. I ran the 3 lines of code. The middle line shows «true» in the Immediate window. That makes sense because I open the userform as vbmodeless so I could double-click the worksheet name and copy each into the userform. When I run the 3rd line, I still get the Copy method of Worksheet class failed.

  • #8

The middle line shows «true» in the Immediate window.

What about the first line?
Debug.Print txtClaimsShtName = Trim(txtClaimsShtName)

Can you show us part of the code that assign the sheet name to txtClaimsFname?

  • #9

What about the first line?
Debug.Print txtClaimsShtName = Trim(txtClaimsShtName)

Can you show us part of the code that assign the sheet name to txtClaimsFname?

My apologies; Both the 1st and 2nd lines return “true.»

The claims file name (txtClaimsFname) is assigned in Sub PostQuestExport1:

With Application.FileDialog(msoFileDialogFilePicker)
.Title = («Find Your HPN Claims File and Click OK»)
‘Makes sure the user can select only one file
.AllowMultiSelect = False
‘Filter to just the following types of files to narrow down selection options
.Filters.Add «Excel Files», «*.xlsx; *.xlsm; *.xls; *.xlsb;*.csv», 1
‘Show the dialog box
‘Store in fullpath variable
If .Show <> 0 Then
txtClaimsFpath = .SelectedItems.Item(1)
txtClaimsFname = Mid(.SelectedItems(1), InStrRev(.SelectedItems(1), «») + 1)
Else
MsgBox («No file was selected. When ready to start again, click the cloud icon.»)
Exit Sub
End If
End With

Sub PostQuestExport1 ends by loading the userform: Form.Show vbModeless
Code from the userform that assigns the worksheet names:

If TextBox6 = «» Then
MsgBox («Paste the claims file tab name here. This field cannot be blank.»)
TextBox6.SetFocus
Exit Sub
Else
txtClaimsShtName = TextBox6.Text
End If

If TextBox7 = «» Then
MsgBox («Paste the Geocoded claims tab name here. This field cannot be blank.»)
TextBox7.SetFocus
Exit Sub
Else
txtGeoClaimsShtName = TextBox7.Text
End If

At the end of this sub, I then pass these values:

Call PostQuestExport2(txtDrive1, txtDiv, CompName, txtClaimsShtName, txtPdColPres, txtPdCol, intHeadrRow, txtGeoClaimsShtName)

Inside PostQuestExport2:

Sub PostQuestExport2(txtDrive1 As String, txtDiv As String, CompName As String, txtClaimsShtName As String, _
txtPdColPres As String, txtPdCol As String, intHeadrRow As Integer, txtGeoClaimsShtName As String)

  • #10

Hi MAM8433. It doesn’t seem like you’re actually opening your selected file. You can trial this code. Please save a back up copy of your wbs before trialing the code. HTH. Dave

Code:

Sub CopySheets()
Dim FileNm As Object, TargetFiles As FileDialog
Dim txtClaimsShtName As String, txtGeoClaimsShtName As String
txtClaimsShtName = TextBox6.Text
txtGeoClaimsShtName = TextBox7.Text

Set TargetFiles = Application.FileDialog(msoFileDialogFilePicker)
With TargetFiles
.Title = ("Find Your HPN Claims File and Click OK")
'Makes sure the user can select only one file
.AllowMultiSelect = False
'Filter to just the following types of files to narrow down selection options
.Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb;*.csv", 1
If .Show = 0 Then
MsgBox ("No file was selected. When ready to start again, click the cloud icon.")
Exit Sub
End If
End With

On Error GoTo below
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'open the file and assign the workbook
Set FileNm = Workbooks.Open(TargetFiles.SelectedItems(1))
Workbooks(FileNm.Name).Worksheets(txtClaimsShtName).Copy _
    After:=Workbooks(txtMacroFname).Worksheets("By Market Report")
Workbooks(FileNm.Name).Worksheets(txtGeoClaimsShtName).Copy _
    After:=Workbooks(txtMacroFname).Worksheets("By Market Report")
Workbooks(FileNm.Name).Close SaveChanges:=False
below:
If Err.Number <> 0 Then
MsgBox "Error"
End If
Set FileNm = Nothing
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

For the first time I now faced the error

Method ‘Copy’ of object ‘_Worksheet’ failed

I heard that this is a quite common error but I was not able to find a solution. When I searched trough SO, I found many posts about the

‘Range’ of object failed-Error.

Is this error caused by memory limitations of the workstation or is it a software related error?

Anyone got an idea to work around that problem?

In case it is of interest that is my VBA code:

Private Sub CommandButton1_Click()
MsgBox "Message"

  Dim wb As Workbook
  Set wb = Workbooks.Add(xlWBATWorksheet)
  wb.Sheets(1).Name = "deletethissheet"

  Dim ws As Worksheet
  For Each ws In ThisWorkbook.Worksheets
    ws.Copy After:=wb.Sheets(wb.Sheets.Count)
  Next

  For Each ws In wb.Worksheets
    ws.UsedRange.Formula = ws.UsedRange.Value

    Dim sh As Shape
    For Each sh In ws.Shapes
      sh.Delete
    Next

  Next

  For Each Link In wb.LinkSources(xlLinkTypeExcelLinks)
  wb.BreakLink Name:=Link, Type:=xlLinkTypeExcelLinks
  Next

  wb.Sheets("deletethissheet").Delete
  wb.SaveAs Replace(ThisWorkbook.FullName, ".xlsm", "_" & Format(Date, "yyyymmdd") & ".xlsx"), xlOpenXMLWorkbook
  wb.Close SaveChanges:=False

End Sub

ws.Copy After:=wb.Sheets(wb.Sheets.Count)
Is the cause of the error.

  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • «Copy method of Worksheet class Failed» — Excel VBA

  1. Sep 30th, 2005, 03:19 AM


    #1

    dale_albiston is offline

    Thread Starter


    Lively Member


    problem:
    I’m trying to copy a wide range of sheets under macro control, well actually two sheets being copied & configured to make a report template.

    The code works fine, upto a point.

    VB Code:

    1. Sub BuildTemplate()

    2.     ' scan set list looking for sets to include

    3.     Dim Row As Integer

    4.     Dim MySheet As Worksheet

    5.     Dim junk As String

    6.     ' remove all sheets *except* the control sheet and the templates

    7.     Application.DisplayAlerts = False

    8.     For Each MySheet In Application.Worksheets

    9.         If MySheet.Name <> "Controls" And MySheet.Name <> "Template-3" And MySheet.Name <> "Template-4" Then

    10.             MySheet.Delete

    11.         End If

    12.     Next

    13.     Application.DisplayAlerts = True

    14.         For Row = 4 To 47

    15.             If Worksheets("Controls").Cells(Row, 1) = "Yes" Then

    16.                 ' set is marked to copy

    17.                 Worksheets("Template-3").Copy before:=Worksheets("Template-3")

    18.                 Set MySheet = Worksheets("Template-3 (2)")

    19.                 MySheet.Range("d6") = Worksheets("Controls").Cells(Row, 2)

    20.                 MySheet.Range("h6") = Worksheets("Controls").Range("d4")

    21.                 MySheet.Range("d8") = Worksheets("Controls").Range("d7")

    22.                 MySheet.Name = Worksheets("Controls").Cells(Row, 2) & "-Data"

    23.                 Worksheets("Template-4").Copy before:=Worksheets("Template-3")

    24.                 Set MySheet = Worksheets("Template-4 (2)")

    25.                 MySheet.Range("C2") = Worksheets("Controls").Cells(Row, 2)

    26.                 MySheet.Range("E2") = Worksheets("Controls").Range("d4")

    27.                 MySheet.Range("C3") = Worksheets("Controls").Range("d7")

    28.                 MySheet.Name = Worksheets("Controls").Cells(Row, 2) & "-Summary"

    29.             End If

    30.         Next Row

    31.     MsgBox ("Templates Created for Selected Sets")

    32. End Sub

    It runs, and runs well for small numbers of sheet to copy,

    the ‘controls’ page holds a two column list, where by a ‘yes’ or ‘no’ is specified next to the target sheets name, it copies the two template pages, configures them and renames them, then moves on to the next one.

    so far its producing around 26 copies ok, then throwing an error.

    Runtime Error 1004
    «Copy method of Worksheet class Failed»

    the help system being somewhat useless with messages like this, the debug window points to one of the two ‘worksheet(x).copy’ lines, not always the same one. Its not the sheet names either since it doesn’t matter which of the records I select it gets so far then dies.

    Given this function has worked fine upto this point, building the first 26 copies fine this is somewhat confusing.

    this alos nukes the copy function totally for coping worksheets manually, it just doesn’t do anything until excel is closed & restarted. Deleting sheets manually doesn’t help so I doubt its an internal sheet limit (is there a limit on how many sheets you can have?)

    any ideas on what could be causing this?

    naturally an ideas on how to resolve it would also be welcome :-)


  2. Sep 30th, 2005, 03:25 AM


    #2

    dale_albiston is offline

    Thread Starter


    Lively Member


    Re: «Copy method of Worksheet class Failed» — Excel VBA

    Further to the above.. I figured a dirty hack, simple have several reports, each with fewer than 26 result sets in it..

    went with ten, ran one ok. saved it..
    ran the second (another 10), gave it a new name, saved it
    the third bombed. as before, even though the origonal sheet is no longer open.

    it looks like worksheet(x).copy runs ‘z’ number of times and thats it without restarting excel… wierd.


  3. Sep 30th, 2005, 08:15 AM


    #3

    Re: «Copy method of Worksheet class Failed» — Excel VBA

    Dale
    I just ran your code 5 time on the same workbook with no errors. It produced 88 templates (44 * 2) each time without throwing any errors — so there nothing wrong with your code.

    Declan

    Don’t forget to mark your Thread as resolved.
    Take a moment to rate posts that you think are helpful


  4. Sep 30th, 2005, 08:52 PM


    #4

    Re: «Copy method of Worksheet class Failed» — Excel VBA

    Quote Originally Posted by DKenny

    Dale
    I just ran your code 5 time on the same workbook with no errors. It produced 88 templates (44 * 2) each time without throwing any errors — so there nothing wrong with your code.

    I did the same. Code’s working fine for me too.

    Think you can attach the workbook that’s giving you the problem???

    If you find any of my posts of good help, please rate it


  5. Oct 3rd, 2005, 02:27 AM


    #5

    dale_albiston is offline

    Thread Starter


    Lively Member


    Re: «Copy method of Worksheet class Failed» — Excel VBA

    Ahem..

    Rename the attached to ‘anything’.xls and it should be ok.

    the trick is to move to the ‘control’ sheet, select which set numbers you wish to generate a template for. then click the button, this will delete everything except the control sheet and the two templates, then build the templates as required.

    The set numbers relate to trains (yawn), for the purposes of testing the sheet the dates and period ranges are not relevent.

    This builds a report template which is then fed to a vb.net program to fill in.

    Its good to hear the code works, its probably something related to the machine here and something to do with a library being corrupt or some such rubbish.

    Typically it bombs around the 26th set on this machine, if it still all works fine its def this flipping machine.. Grrrr..

    Thanks for testing it though :-)


  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • «Copy method of Worksheet class Failed» — Excel VBA


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Копирование некоторых листов в новую книгу с заменой типов я

akaDemik

Дата: Вторник, 29.09.2015, 11:07 |
Сообщение № 1

Группа: Пользователи

Ранг: Участник

Сообщений: 67


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

Доброго времени суток!
С формулами я более-менее знаком, но понадобилась рутинная работа, с которой должен справляться макрос.
Задача: В книге 10 листов, 6 из них необходимо скопировать в новые книги, каждая отдельным файлом, после этого необходимо заменить тип ячеек с «формула» на «значение»
в интернетах нашел макрос
[vba]

Код

Sub SplitSheets2()
     Dim s As Worksheet
     Set wb = ActiveWorkbook
     For Each s In wb.Worksheets                    
         s.Copy                    
         ActiveWorkbook.SaveAs wb.Path & «» & s.Name & Format(Now, «DD-MM-YYYY») & «.xlsx»  

          Next
End Sub

[/vba]
в принципе он с задачей справился, но наполовину т.к. надо в название файла подставлять немного другой формат даты не «ДД-ММ-ГГГГ» а «ГГГГ-ММ-ДД» + название Листа. В идеале надо не копировать все листы, а только 6 из 10
В конце данного макроса выбивает еще ошибку

Цитата

Run-time error ‘1004’
Method ‘Copy’ of object’_Worksheet’ failed

Еще не могу найти нужный пример выбора всех ячеек на листе чтобы применить
[vba]

Код

cell.Formula = cell.Value

[/vba]

 

Ответить

Manyasha

Дата: Вторник, 29.09.2015, 13:15 |
Сообщение № 2

Группа: Модераторы

Ранг: Старожил

Сообщений: 2198


Репутация:

898

±

Замечаний:
0% ±


Excel 2010, 2016

akaDemik, вот так попробуйте:
[vba]

Код

Sub SplitSheets2()
     Dim s As Worksheet
     Set wb = ActiveWorkbook
     For Each s In wb.Sheets(Array(«Лист1», «Лист2»)) ‘остальные листы допишите
         s.Copy
         ActiveSheet.UsedRange = ActiveSheet.UsedRange.Value
         ActiveWorkbook.SaveAs wb.Path & «» & Format(Now, «YYYY-MM-DD») & «-» & s.Name & «.xlsx»
     Next
End Sub

[/vba]


ЯД: 410013299366744 WM: R193491431804

 

Ответить

akaDemik

Дата: Вторник, 29.09.2015, 14:40 |
Сообщение № 3

Группа: Пользователи

Ранг: Участник

Сообщений: 67


Репутация:

0

±

Замечаний:
0% ±


Excel 2010


т.к. у меня листы переименованы, с начала выдало ошибку, потом понял что надо подправить название в коде)
благодарю
осталось понять почему выдавало ошибку
[vba]

Код

Run-time error ‘1004’
Method ‘Copy’ of object’_Worksheet’ failed

[/vba]

 

Ответить

Manyasha

Дата: Вторник, 29.09.2015, 15:08 |
Сообщение № 4

Группа: Модераторы

Ранг: Старожил

Сообщений: 2198


Репутация:

898

±

Замечаний:
0% ±


Excel 2010, 2016

akaDemik, Ваш исходный макрос у меня такой ошибки не выдавал. :o


ЯД: 410013299366744 WM: R193491431804

 

Ответить

akaDemik

Дата: Вторник, 29.09.2015, 15:49 |
Сообщение № 5

Группа: Пользователи

Ранг: Участник

Сообщений: 67


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

Manyasha, странно…
тут еще появилась новая вводная, т.к. функция YYYY-MM-DD подставляет текущий день, то иногда надо будет прописать дату с ячейки, при этом эта ячейка состоит из формулы, ее также надо преобразовать в значение

 

Ответить

akaDemik

Дата: Вторник, 29.09.2015, 16:23 |
Сообщение № 6

Группа: Пользователи

Ранг: Участник

Сообщений: 67


Репутация:

0

±

Замечаний:
0% ±


Excel 2010

надо будет прописать дату с ячейки, при этом эта ячейка состоит из формулы, ее также надо преобразовать в значение

сам задал вопрос, сам и отвечаю))
[vba]

Код

ActiveWorkbook.SaveAs wb.Path & «» & Format(wb.Sheets(«Лист1»).Range(«G3»)) & «_» & s.Name & «.xlsx»

[/vba]
макрос понял что надо подставить результат, а не формулу

 

Ответить

  • Home
  • Forum
  • VBA Code & Other Help
  • Excel Help
  • Method ‘Copy’ of object’_Worksheet’ failed PROBLEM

  1. 09-18-2017, 03:55 AM


    #1

    Method ‘Copy’ of object’_Worksheet’ failed PROBLEM

    Trying to create a new workbook but the Method ‘Copy’ of object’_Worksheet’ failed error keeps preventing the copy process.
    I’ve attached a workbook. The Macro is run from the NewMODSheet WorkSheet.

    The Button says » Add A New WorkBook»

    Caution! The attached worksheet crashes when the Macro runs.
    But at the bottom of the sheet it shows copying.
    A new Book1 is created, but it’s hidden from view, and the worksheet crashes.

    The same code works on other sheets.


  2. 09-18-2017, 04:42 AM


    #2

    It doesn’t crash for me, though of course you will get prompted about removing the VB project as you are trying to save a workbook with code in it as an xlsx file. Also, you really ought to specify the file format parameter.


  3. 09-18-2017, 03:30 PM


    #3

    Hi Aflatoon:

    I have tried to save in every format I can think of, including

    ActiveWorkbook.SaveAs "C:GraphicSheetTest.xls", FileFormat:=56

    The line that causing the problem is the Copy portion of the code;

    Sheets(Array("NewMODSheet", "Sheet2")).Copy

    I’m still not sure what’s the problem.


  4. 09-19-2017, 02:13 AM


    #4

    Newer versions of Windows will not allow you to save a file to the Root directory. Try another folder.

    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.

    To help indent your macros try Smart Indent

    Please remember to mark threads ‘Solved’


  5. 09-20-2017, 11:16 PM


    #5

    mdmackillop:

    I have already tried that.
    ActiveWorkbook.SaveAs «C:DailyGraphicSheetTest.xls», FileFormat:=56

    Same exact error at the same location. Were you able to get it to save?


  6. 09-21-2017, 03:38 AM


    #6

    No issues with either of these:

    ActiveWorkbook.SaveAs "C:VBAXGraphicSheetTest.xlsm", FileFormat:=52
    ActiveWorkbook.SaveAs "C:VBAXGraphicSheetTest.xls", FileFormat:=56

    As a last resort try

    Worksheets(Array("NewMODSheet", "Sheet2")).Copy

    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.

    To help indent your macros try Smart Indent

    Please remember to mark threads ‘Solved’


  7. 11-14-2017, 05:41 PM


    #7

    Thanks mdmackillop;

    I was away from Computers for a while. Traveling & A minor medical issue. Now, back to work.



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules

Like this post? Please share to your friends:
  • Excel vba copy cell and paste
  • Excel vba copy all sheets to one sheet
  • Excel vba convert to string
  • Excel vba control type
  • Excel vba const array