从其他工作簿复制工作表时出错

时间:2018-01-25 11:30:55

标签: excel-vba vba excel

我只看到很多文章,但我找不到问题的答案。

我必须将一张纸从文件A复制到文件B.当程序复制纸张时,我有error 10040

代码如下:

Private Sub CommandButton1_Click()
Dim numsheets As Integer
Dim nmp As Integer
Dim WB As Workbook 'Is the target workbook
Dim WB_prov As Workbook 'Is the source workbook
Dim SH As Worksheet
Dim SH_prov As Worksheet 'Is the sheet to copy
Dim CurrentSN As String 'Is the name of the sheets to import

Set WB = ActiveWorkbook
Set SH = WB.ActiveSheet

'Open the source file
Application.DisplayAlerts = False
Set App = New Excel.Application
Set WB_prov = App.Workbooks.Open("C:\Users\roberto\Documents\tav7_2017_7.xlsm")
Set sh1 = WB_prov.Sheets("TabellaMansioni")

'Read number of sheets to insert
NumMan = SH.Range("A31")
RR1 = sh1.Range("A" & Rows.Count).End(xlUp).Rows



'Primo controllo sull'esistenza dei codici
For i = 2 To (2 + NumMan)
    For j = 2 To RR1
        If SH.Range("B" & i) = sh1.Range("B" & j) Then
        Else
            MsgBox ("Il codice non è presente in archivio.")
            GoTo Chiusura
        End If
    Next
Next

**'Insert sheets
For i = 2 To (2 + NumMan)
    CurrentSN = SH.Range("B" & i).Value
    Set SH_prov = WB_prov.Sheets(CurrentSN)
    SH_prov.Copy After:=WB.Sheets("Riepilogo") *'In this line error 1004*
Next**

你有什么建议吗?

感谢。

1 个答案:

答案 0 :(得分:1)

您尚未在模块顶部添加Option Explicit,因此可以动态创建变量(即不首先声明变量)。
例如您已使用SHsh1在代码中使用SH作为工作表进行了宣传App。您尚未声明NumMansh1RR1ijSet App = New Excel.Application

我认为这是阻止你的代码工作的一点
您已使用Set App = New Excel.Application创建了一个新的Excel实例,因此这两个工作簿位于不同的实例中。

没有测试:

  • 我摆脱了Set WB_prov = App.Workbooks.Open("C:\Users\roberto\Documents\tav7_2017_7.xlsm")
  • 更改
    Set WB_prov = Workbooks.Open("C:\Users\roberto\Documents\tav7_2017_7.xlsm")
    Sub Test() Dim WB As Workbook Dim SH As Worksheet Dim WB_prov As Workbook Dim SH_prov As Worksheet Set WB = ThisWorkbook 'The workbook containing the code. Set SH = WB.Worksheets(1) 'Reference to first sheet in tab order. Set WB_prov = Workbooks.Add 'This will be created in the same instane of Excel as WB. Set SH_prov = WB_prov.Worksheets(1) SH_prov.Name = "UniqueName" 'Copy UniqueName from the new workbook to after the first worksheet in the WB workbook. SH_prov.Copy After:=SH End Sub

将工作表从一个工作簿复制到另一个工作簿的基本示例:

find $Directory -type f -name "patch_data.conf" -exec sed -i "s,${stringreplace},${stringnew},g" {} \;