简体   繁体   English

导入Excel宏并与VBS一起运行

[英]Import Excel Macro and run it with VBS

I would like to create a vbs script that will open an .xlsx document, import a macro and run the macro. 我想创建一个vbs脚本,它将打开一个.xlsx文档,导入一个宏并运行该宏。 For my use, the .xlsx document's name will vary - so I may need a wildcard for the filename. 对于我的使用,.xlsx文档的名称会有所不同-因此我可能需要使用通配符作为文件名。 This is what I have so far: 这是我到目前为止的内容:

Set xl = CreateObject("Excel.application")
xl.Application.Workbooks.Open "\\path\Missed_Scans\Report\Report.xlsx"
xl.Application.Visible = True
x1.VBProject.VBComponents.Import "\\path\Missed_Scans\Missed_Scans.bas"
x1.Save
xl.Application.run "'Report.xlsx'!Missed_Scans"
Set xl = Nothing

The above script will open 'report.xlsx' but it does not seem to correctly import or run the macro. 上面的脚本将打开“ report.xlsx”,但它似乎无法正确导入或运行宏。 It is not necessary for report.xlsx to be opened (visibly or otherwise) so long as the macro is imported and run. 只要导入并运行宏,就不必打开(可见或其他方式)report.xlsx。

EDIT 编辑

Here is the macro: 这是宏:

Attribute VB_Name = "Module1"
Sub Missed_Scans()
Attribute Missed_Scans.VB_ProcData.VB_Invoke_Func = " \n14"
'
' Missed_Scans Macro
'

'
    Sheets("Incomplete_ASINs").Select
    ActiveSheet.Range("$A$1:$J$52951").AutoFilter Field:=1, Criteria1:="SDF8"
    Columns("B:D").Select
    Selection.Copy
    Workbooks.Add
    ActiveSheet.Paste
    Rows("1:1").Select
    Application.CutCopyMode = False
    Selection.AutoFilter
    ActiveWorkbook.SaveAs Filename:="\\path\Missed_Scans\Report\Missed_Scans.xlsx" _
        , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    ActiveWindow.Close
End Sub

Thanks! 谢谢!

Your code may well be giving issues due to the use of x1 which hasn't been set. 由于未使用x1 ,因此您的代码很可能会出现问题。

You probably intended to use 您可能打算使用

Set x1 = xl.Application.Workbooks.Open("\\path\Missed_Scans\Report\Report.xlsx")

But I would have expected that to actually crash rather than just not correctly importing the macro. 但是我希望它实际上会崩溃,而不是不正确地导入宏。


I suspect that you can avoid using the VBA macro if you just use the equivalent code in VBS: 我怀疑如果仅在VBS中使用等效代码,就可以避免使用VBA宏:

Set xl = CreateObject("Excel.application")
xl.Application.Visible = True

Dim wb1
Set wb1 = xl.Application.Workbooks.Open("\\path\Missed_Scans\Report\Report.xlsx")
Dim wb2
Set wb2 = xl.Workbooks.Add

wb1.Sheets("Incomplete_ASINs").Range("$A$1:$J$52951").AutoFilter 1, "SDF8"
wb1.Sheets("Incomplete_ASINs").Columns("B:D").Copy
wb2.Worksheets(1).Paste
wb2.Worksheets(1).Rows(1).AutoFilter
wb2.SaveAs "\\path\Missed_Scans\Report\Missed_Scans.xlsx", 51, , , , False
wb2.Close
wb1.close
xl.Quit
Set xl = Nothing

Note: I'm not an expert in VBS, so I hope that code works. 注意:我不是VBS专家,所以我希望代码能正常工作。 Let me know if it doesn't. 让我知道是否可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM