在Excel文件(xlsm)中执行的代码可以完美地工作
Sub insertObject()
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("YourPath\Datasheet.xlsx")
objExcel.Application.Visible = True
objWorkbook.ActiveSheet.OLEObjects.Add(Filename:="YourPath\Placeholder.txt", _
Link:=False, DisplayAsIcon:=True, IconFileName:= _
"C:\Windows\system32\packager.dll", IconIndex:=0, IconLabel:= _
"C:\Placeholder.txt").Select
objWorkbook.SaveAs "yourPath\test.xlsx"
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
WScript.Quit
End Sub
这是我尝试使用vbs脚本执行的代码
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("YourPath\Datasheet.xlsx")
objExcel.Application.Visible = True
ActiveSheet.OLEObjects.Add(Filename:="YourPath\Placeholder.txt", _
Link:=False, DisplayAsIcon:=True, IconFileName:= _
"C:\Windows\system32\packager.dll", IconIndex:=0, IconLabel:= _
"C:\Placeholder.txt").Select
objWorkbook.SaveAs "YourPath\test.xlsx"
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
WScript.Quit
我用真正的路径替换了路径,当然,代码在宏内可以正常工作,但是当我尝试使用cmd命令运行它时,在vbs脚本内却失败了。
答案 0 :(得分:1)
运行您的代码时,我会得到相同的结果。我尝试了一些不同的调整,并且有效: 您只是忘记了OLEobject的add函数的第一个参数,而别忘了删除参数名称:
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("YourPath\Datasheet.xlsx")
objExcel.Application.Visible = false
Set ob = objWorkbook.ActiveSheet.OLEObjects
Set t = ob.Add (,"YourPath\Placeholder.txt",False, True, "C:\Windows\system32\packager.dll", 0,"C:\Placeholder.txt")