复制列时自动打开和关闭Excel文件

时间:2016-06-23 10:30:39

标签: vbscript

我有一个VB脚本,它将两个列从一个excel复制到另一个excel文件的相同列。这样做,它打开了 excel文件,我不想要。最好是,我希望这在背景中发生,如果不可能,那么我希望它自动关闭它 完成程序后。 我试图更新我的代码来完成这个任务,但它已经开始抛出弹出窗口。其中一个读为 “剪贴板中有大量信息......”然后第二个弹出窗口询问我是否要保存文件中的更改。 我自动想要这一切,没有手动互动。 我希望整个程序在没有任何人工干预的情况下发生

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open("C:\Desktop\Folder1\Customer.xlsx")
Set objWorkbook2 = objExcel.Workbooks.Open("C:\Documents\Folder2\New_Customer.xlsx")

Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Activate

Set objRange = objWorkSheet.Range("A:B").EntireColumn
objWorkSheet.Range("A:B").EntireColumn.Copy

Set objWorksheet2 = objWorkbook2.Worksheets(1)
objWorksheet.Activate

Set objRange = objWorkSheet2.Range("A:B")
objWorkSheet2.Paste objWorkSheet2.Range("A:B")
objWorksheet.Paste(objRange)

objworkbook.Saved = True

objWorkbook.close("C:\Desktop\Folder1\Customer.xlsx")
objWorkbook2.close("C:\Documents\Folder2\New_Customer.xlsx")

我的输入文件如下:

Customer Number    Customer Name
1001    Wendy
1002    Subway
1003    McDonalds

1 个答案:

答案 0 :(得分:0)

你很亲密。以下解决方案应该做你想做的事 请注意:

  • objworkbook.Saved = True - 这意味着不想保存任何更改
  • objworkbook.Save - 这意味着您要保存更改

我在下面的代码中添加了两行,因此您可以选择您想要的那一行并删除另一行。

编辑:我更新了以下代码。 我假设您要放弃objWorkbook中的任何更改并将更改保存到objWorkbook2 我不明白你在objWorkbook.close部分想要做什么,但我保持不变。

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False   ' This is the value that decides if process should run on background or not. Keep as False if you don't want to display the application
Set objWorkbook = objExcel.Workbooks.Open("C:\Desktop\Folder1\Customer.xlsx")
Set objWorkbook2 = objExcel.Workbooks.Open("C:\Documents\Folder2\New_Customer.xlsx")

Set objWorksheet = objWorkbook.Worksheets(1)
Set objWorksheet2 = objWorkbook2.Worksheets(1)

objWorksheet.Range("A:B").EntireColumn.Copy
objWorksheet2.Paste objWorksheet2.Range("A1")

objExcel.DisplayAlerts = False ' This will make Excel stop showing any warnings
objworkbook.Saved = True  ' This means you don't want to save changes
objWorkbook2.Save         ' This means you want to save changes.

' I don't understand what you are trying to do here, but I'm not changing this
objWorkbook.close("C:\Desktop\Folder1\IHT_PIM_STATUS_TEST.xlsx\Customer.xlsx")
objWorkbook2.close("C:\Documents\Folder2\New_Customer.xlsx")

objExcel.Quit    ' Close excel application after the whole process