Windows脚本打开Excel文件并运行宏

时间:2016-06-21 11:08:56

标签: excel vba excel-vba vbscript

对不起,我对VBA很新,所以我一直在学习。我试图寻找一个答案,但我发现的一切似乎都认为宏将在我想要打开的文件中。

每月一次我收到一个包含一些数据的文件。到目前为止,我不得不查看数据然后执行VLOOKUP以在保存之前添加一些其他数据。

我现在已经编写了一个VBA宏来添加我想要的其他信息,它可以按预期工作。但是,我想要做的是有一个Windows脚本,它将打开我收到的文件,运行我写的宏,然后将文件保存为csv。

有人能指出我正确的方向吗?如果需要,我的宏位于

之下
Sub AddBandInfo()
Dim i As Long
For i = 2 To 50000
Dim band As String, result As Double
band = Range("B" & i).Value
If band = "A" Then result = 1144.02
If band = "B" Then result = 1334.7
If band = "C" Then result = 1525.36
If band = "D" Then result = 1716.04
If band = "E" Then result = 2097.38
If band = "F" Then result = 2478.72
If band = "G" Then result = 2860.08
If band = "H" Then result = 3432.08
If band = "" Then result = 0.01
Range("C" & i).Value = result
Next i

Dim r As Long
For r = Sheet1.UsedRange.Rows.Count To 1 Step -1
If Cells(r, "C") = "0.01" Then
    Sheet1.Rows(r).EntireRow.Delete
End If
Next

End Sub

由于

2 个答案:

答案 0 :(得分:0)

创建.txt文件并将其重命名为.vbs。

使用以下代码启动代码:

Set objXLS = CreateObject("Excel.Application")
Set myWkbk = objXLS.Application.Workbooks.Open("C:\mypath\myfile.xlsx")
Set myWksh = myWkbk.Worksheets("yoursheet")
With myWksh

'your
'code
'here

End With

Set objXLS = Nothing

全部完成。 :)

答案 1 :(得分:0)

我们可以通过

提高AddBandInfo的速度和性能
  • 切换Application.ScreenUpdating
  • 从最后一行循环到第一行(这样做可以用来删除行)

如果50000不是实际的最后一行,请使用

  

对于i = Range(“B”& Rows.Count).End(xlUp).Row To 2 Step -1

Public Sub AddBandInfo()
    Dim i As Long
    Application.ScreenUpdating = False
    For i = 50000 To 2 Step -1
        Dim band As String, result As Double
        band = Range("B" & i).Value
        Select Case Cells(i, 2).Value
            Case "A"
                Range("C" & i).Value = 1144.02
            Case "B"
                Range("C" & i).Value = 1334.7
            Case "C"
                Range("C" & i).Value = 1525.36
            Case "D"
                Range("C" & i).Value = 1716.04
            Case "E"
                Range("C" & i).Value = 2097.38
            Case "F"
                Range("C" & i).Value = 2478.72
            Case "G"
                Range("C" & i).Value = 2860.08
            Case "H"
                Range("C" & i).Value = 3432.08
            Case Else
                Rows(i).EntireRow.Delete
        End Select
    Next
    Application.ScreenUpdating = True
End Sub

假设AddBandInfo保存在C:\ somedirectory \ somefile.xlsx中,并且您希望vbscript打开Workbook然后运行AddBandInfo:

Const WorkBookPath = "C:\somedirectory\somefile.xlsx"
Dim xlApplication, xlWorkbook

Set xlApplication = CreateObject("Excel.Application")
Set xlWorkbook = xlApplication.Workbooks.Open(WorkBookPath)
xlApplication.Run "'" & xlWorkbook.Name & "'!AddBandInfo()"

xlWorkbook.Save , False
xlApplication.Quit

Set xlApplication = Nothing