Excel Vba复制方法的工作表失败

时间:2012-02-17 11:41:44

标签: excel excel-vba vba

我正在尝试将excel表从一个工作簿复制到另一个工作簿,而用户没有看到任何内容,但我不断收到错误“工作表类的复制方法失败”。除非工作簿可见,否则您似乎无法将一个工作表复制到另一个工作簿?

感谢您的帮助。

她的代码失败了:

Private Sub CommandButton1_Click()

Dim xlapp As Excel.Application
Dim wkBook As Excel.Workbook

'Connect to Excel
Set xlapp = New Excel.Application

'Set workbook and open workbook in directory
Set wkBook = xlapp.Workbooks.Open(sFileName, xlUpdateLinksNever, ReadOnly:=False)


ThisWorkbook.Sheets("Logistics").Copy Before:=wkBook.Sheets(1)

wkBook.Close True
xlapp.Quit
Set xlapp = Nothing

End Sub

4 个答案:

答案 0 :(得分:2)

如果从Excel执行此操作,则无需调用Excel.Application,这应该可以正常工作:

Private Sub CommandButton1_Click()

  Dim wkBook As Workbook

  'Set workbook and open workbook in directory
  Set wkBook = Workbooks.Open(sFileName, xlUpdateLinksNever, ReadOnly:=False)

  ThisWorkbook.Sheets("Logistics").Copy Before:=wkBook.Sheets(1)

  wkBook.Close True

End Sub

如果您需要与代码类似的东西,则需要使用当前的Excel Workbook for ThisWorkbook指向正确的工作簿:

Set xlapp = ThisWorkbook.Application

如果您需要在没有用户看到更改的情况下执行此操作,您可以使用:

Application.ScreenUpdating = False
'Insert the rest of the code
Application.ScreenUpdating = True

答案 1 :(得分:2)

如果您想在后台执行此操作,则应使用控制工作簿自动执行两个工作簿

最好再次将其作为而不是

运行
  1. 将此代码复制到NotePad
  2. 更改源和目​​标工作簿的路径以适合
  3. 将其另存为vbs文件,即“test.vbs”
  4. 单击vbs文件以在后台执行副本
  5. 或者将此代码放在VBA中的Sub中并在控制工作簿中运行它,同时关闭源文件和目标文件(如果使用VBA,建议您正确地对变量进行维度)

    Dim objExcel
    Dim Wb1
    Dim Wb2
    Dim ws
    Set objExcel = CreateObject("excel.application")
    On Error Resume Next
    Set Wb1 = objExcel.Workbooks.Open("c:\temp\source.xlsm")
    Set Wb2 = objExcel.Workbooks.Open("c:\temp\dest.xlsm")
    Set ws = Wb1.Sheets("logistics")
    If Not IsEmpty(ws) Then
        ws.Copy Wb2.Sheets(1)
        objExcel.DisplayAlerts = False
        Wb2.Save
        objExcel.DisplayAlerts = True
        wscript.echo "success"
    Else
        wscript.echo "copy failed"
    End If
    Wb2.Close False
    Wb1.Close False
    On Error GoTo 0
    objExcel.Quit
    Set objExcel = Nothing
    

答案 2 :(得分:2)

  
    
      

但是我不希望用户看到工作簿的打开和关闭?有没有办法从一个工作簿复制到另一个工作簿而无需用户看到正在复制到的工作簿?谢谢 - JC75

             

我需要将工作簿设置为visible = false,但工作簿没有可见属性。如果我将应用程序窗口设置为visible = false,我会得到“工作表类的复制方法失败”的相同原始错误 - JC75

    
  

实现你想要的另一种方式。

'~~> From within excel
Sub Sample()
    Dim wb1 As Workbook, wb2 As Workbook
    Dim ws1 As Worksheet
    Dim sFileName As String

    sFileName = "C:\Temp.xls"

    Set wb1 = ActiveWorkbook
    Set ws1 = wb1.Sheets("Logistics")

    Set wb2 = Workbooks.Open(sFileName)
    ActiveWindow.Visible = False

    wb2.Sheets.Add Before:=wb2.Sheets(1)
    ws1.Cells.Copy wb2.Sheets(1).Cells

    'Windows(wb2.Name).Visible = True
    wb2.Close SaveChanges:=True

    Set wb1 = Nothing
    Set wb2 = Nothing
End Sub

答案 3 :(得分:1)

试试这个

Sub CopyAcross()
  Workbooks("Model24.xls").Sheets("Custom").Copy Before:=Workbooks("Master.xls").Sheets(1)
End Sub