如何为特定的excel文件运行外部vbs文件

时间:2013-04-12 12:02:25

标签: excel vbscript

我已经写了一个vbs代码

Sub rectangle()
    With ActiveSheet.Shapes.AddShape(msoShapeRectangle, 10, 10, 200, 100).TextFrame
        .Characters.Text = "This is a rectangle"
        .HorizontalAlignment = xlHAlignCenter
        .VerticalAlignment = xlVAlignCenter
        ChDir "D:"
        ActiveWorkbook.SaveAs Filename:="D:\Book.xls", _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
        ActiveWorkbook.Save
    End With
    ActiveWorkbook.Save
    Range("F5").Select
End Sub

但是收到错误

script: D:\test.vbs
Line: 10
Char: 36
Error: Expected statement
Code: 800A0400
Source: Microsoft VBscript Compilation error

我已将excel文件和vb文件粘贴到 D 驱动器中。谁能纠正我?

1 个答案:

答案 0 :(得分:2)

我将在.vbs文件中执行此操作。

Const xlHAlignCenter = -4108
Const xlVAlignCenter = -4108
Const xlOpenXMLWorkbookMacroEnabled = 52
Const msoShapeRectangle = 1

Dim oXLApp, oXLWB, oXLWs

Set oXLApp = CreateObject("Excel.Application")

'<~~ I am adding a new workbook for demonstration purpose. 
'<~~ You can open one if you want
Set oXLWB = oXLApp.Workbooks.Add 
Set oXLWs = oXLWB.Sheets("Sheet1")

oXLApp.Visible = True

With oXLWs
    With .Shapes.AddShape(msoShapeRectangle, 10, 10, 200, 100).TextFrame

        .Characters.Text = "This is a rectangle"
        .HorizontalAlignment = xlHAlignCenter
        .VerticalAlignment = xlVAlignCenter

    End With
End With

oXLWB.SaveAs "D:\Book.xls", xlOpenXMLWorkbookMacroEnabled, , , , False