簡體   English   中英

錯誤 1004 VBA 將 Excel 4.0 工作表復制到 Excel 2010

[英]Error 1004 VBA copy Excel 4.0 worksheet to Excel 2010

我編寫了一些托管在 Access 2010 中的 VBA 代碼來清理包含不需要的 AutoRun 宏的 Excel 4.0 工作簿 - 因為我只對數據感興趣,所以將特定工作表復制到新的 Excel 2010 工作簿似乎是個好主意.

但是,當 VBA 到達.Copy語句時,出現錯誤:

1004 對象 '_Worksheet' 的方法 'Copy' 失敗。

這不是具有多個副本的 MS 錯誤,也不是復制前未保存等。這是試圖復制到現有工作簿中。 雖然此錯誤代碼在這里似乎很流行,但我找不到適合我的方法和/或答案。

代碼有問題的部分:

'declarations
Dim varFile As Variant
Dim varNewFile As Variant
Dim xlApp As Excel.Application
Dim xlWbk As Excel.Workbook
Dim xlWb2 As Excel.Workbook
Dim xlSht As Excel.Worksheet
Dim xlSh2 As Object 'will be a member of the Sheets collection (not worksheets)

'filenames - constPath is a constant defining the pathname to the folder
varFile = constPath & "\site.xls"
varNewFile = constPath & "\sitenew.xlsx"

'create instance of Excel, open source workbook and point to worksheet
Set xlApp = CreateObject("Excel.Application")
Set xlWbk = GetObject(varFile)
Set xlSht = xlWbk.Worksheets("sites")

'open destination workbook (already exists)
Set xlWb2 = GetObject(varNewFile)
    
    'rename worksheet with same name
    For Each xlSh2 In xlWb2.Sheets
        If xlSh2.Name = "sites" Then
            xlSh2.Name = "sitesOLD"
        End If
    Next xlSh2
    
'this next statement is where it fails
    'copy across worksheet into existing workbook
    xlSht.Copy Before:=xlWb2.Sheets(1)

我已經檢查了源數據,並且單元格值在長度方面似乎沒有問題(它是名稱和地址信息,加上一些是/否指示符)。

這可能有很多原因。 放 xlApp.xlSht.Copy 有用嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM