.vbs(脚本)用于将整个工作表从文件复制到另一个文件

时间:2017-04-17 21:29:43

标签: excel vbscript

我可以使用什么.vbs代码将整个工作表从excel文件复制到另一个?

我已尝试使用以下内容,但第2行和第3行会弹出错误(Error Image),如果没有它们,脚本会运行但不执行任何操作。

    Sub Copy_Sheet()
    Dim x As Workbook
    Dim y As Workbook

    Set x = Workbooks.Open("C:\File1.xls")
    Set y = Workbooks.Open("C:\File2.xlsx")

    y.Sheets("Sheet1").Range("A1").Value = x.Sheets("Sheet1").Range("A1")

    y.Save
    y.close
    x.Close

    End Sub

3 个答案:

答案 0 :(得分:1)

Dim xlapp ' as excel object 
Dim WSx, WSy ' as excel worksheet 
Dim x, y ' as workbook 
Set xlapp = CreateObject("Excel.Application")
Set x = xlapp.Workbooks.Open("C:\File1.xls")
Set y = xlapp.Workbooks.Open("C:\File2.xlsx") 
Set WSx = x.Worksheets("Sheet1") 
Set WSy = y.Worksheets("Sheet1")
WSx.Copy WSy ' copy worksheet to other workbook
Set WSx = nothing 
Set WSy = nothing 
y.Save 
y.close 
x.Close

这应该将工作表从x复制到y而没有任何问题。

答案 1 :(得分:0)

你可以试试这个

Dim xlapp ' as excel object
Dim WSx, WSy ' as excel worksheet
Dim x, y ' as workbook

Set xlapp = CreateObject("Excel.Application")

Set x = xlapp.Workbooks.Open("C:\File1.xls")
Set y = xlapp.Workbooks.Open("C:\File2.xlsx")
Set WSx = x.Worksheets("Sheet1")
Set WSy = y.Worksheets("Sheet1")

WSy.Range("A1").value = WSx.Range("A1").value

Set WSx = nothing
Set WSy = nothing

y.Save
y.close
x.Close

答案 2 :(得分:0)

VBA键入Dims,如

Dim x As Workbook

在VBScript中是非法的(对于VB和VBS之间的差异,开始阅读here)。这解释了错误。