VBScript复制列到最后一行

时间:2017-10-20 21:09:14

标签: excel vba vbscript

我有一个包含1个标题的电子表格,我试图将数据从排除标题复制到另一个包含2个标题的工作簿中的另一个工作表。我在网上找到了这段代码,但它给了我一个错误,说明有一个预期的'''在第25行。

  copyLastrow = ws1.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row

在这附近:

 searchorder:=xlByRows

这是脚本:

Const FILE1 = "C:\Users\roperalta\Desktop\Book1.xlsx"
Const FILE2 = "C:\Users\roperalta\Desktop\PBJ_Excel_to_XML_Template_v_2_00_3.xlsx"

Dim LastRow
Dim xlApp 
Set xlApp = CreateObject("Excel.Application")

Dim wb1, wb2
With xlApp
    .Visible = False
    .DisplayAlerts = False
    Set wb1 = .Workbooks.Open(FILE1, 0, False)
    Set wb2 = .Workbooks.Open(FILE2, 0, False)
End With

Dim ws1, ws2
Set ws1 = wb1.Sheets("Sheet0 (2)")
Set ws2 = wb2.Sheets("Header")

ws2.Range("B3:D3").Value2 = ws1.Range("B2:D2").Value2

Set ws1 = wb1.Sheets("Sheet0")
Set ws2 = wb2.Sheets("Employees")

copyLastrow = ws1.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row

pasteLastrowG = ws2.Range("A" & Rows.Count).End(xlUp).Row + 1
'pasteLastrowH ...
'pasteLastrowI ...

ws1.Range("J" & copyLastrow).Copy Destination:=ws2.Range("A" & pasteLastrowG)
'Copy and paste B code here
'Copy and paste C code here

wb2.Save
wb1.Close
'wb2.Close
'xlApp.Quit

Set ws1 = Nothing
Set ws2 = Nothing
Set wb1 = Nothing
'Set wb2 = Nothing
'Set xlApp = Nothing

1 个答案:

答案 0 :(得分:0)

VBScript不允许使用名称参数,也不知道Excel.Application NameSpace。因此,您需要完全限定对Excel.Application对象的所有引用,无论如何您都应该这样做。同样,您应该声明Const变量来替换Excel.Application枚举和常量。

Const FILE1 = "C:\Users\roperalta\Desktop\Book1.xlsx"
Const FILE2 = "C:\Users\roperalta\Desktop\PBJ_Excel_to_XML_Template_v_2_00_3.xlsx"
Const xlPrevious = 2
Const xlByRows = 1
Dim LastRow
Dim xlApp, wb1, wb2, ws1, ws2
Set xlApp = CreateObject("Excel.Application")

With xlApp
    .Visible = False
    .DisplayAlerts = False
    Set wb1 = .Workbooks.Open(FILE1, 0, False)
    Set wb2 = .Workbooks.Open(FILE2, 0, False)
End With

Set ws1 = wb1.Sheets("Sheet0 (2)")
Set ws2 = wb2.Sheets("Header")

ws2.Range("B3:D3").Value2 = ws1.Range("B2:D2").Value2

Set ws1 = wb1.Sheets("Sheet0")
Set ws2 = wb2.Sheets("Employees")

copyLastrow = ws1.Cells.Find("*", , , , xlByRows, xlPrevious).Row

pasteLastrowG = ws2.Range("A" & Rows.Count).End(xlUp).Row + 1
'pasteLastrowH ...
'pasteLastrowI ...

ws1.Range("J" & copyLastrow).Copy ws2.Range("A" & pasteLastrowG)
'Copy and paste B code here
'Copy and paste C code here

wb2.Close True
wb1.Close False
xlApp.Quit