在Powershell脚本中嵌入Excel VBA脚本

时间:2015-08-10 23:55:22

标签: excel vba excel-vba powershell

我编写了一个Powershell脚本,该脚本从Exchange Online查询我的所有组,然后获取每个组的成员身份,并将每个组保存到单独的CSV文件中。这一切都很好。 (为简洁起见,省略了一些不相关的部分):

$excelTemplate = "$($fileLocation)\group-breakout.xlsm"
Copy-Item $excelTemplate "$($tempPath)\group-breakout-$($curDate).xlsm"

# Creating Excel COM Object
$excel = new-object -comobject excel.application
$excelFile = Get-ChildItem -Path C:\temp\group-breakout -Include *.xlsm -Recurse

# Gathering all groups:
Write-Host "Getting all groups from Exchange Online..."
$allGroups = Get-DistributionGroup | select Name, PrimarySmtpAddress, ManagedBy, MemberJoinRestriction 
$allGroups | Export-Csv "$($tempPath)\1-AllGroups.csv" -NoTypeInformation
Write-Host "`tDone."
# Gathering members for all groups
Write-Host "Getting members for all groups from Exchange Online..."
$allGroups | ForEach-Object {
    Get-DistributionGroupMember -Identity $_.Name | select DisplayName, Alias, PrimarySmtpAddress | Export-Csv "$($tempPath)\$($_.name.Replace("/","-")).csv" -NoTypeInformation
    }
Write-Host "`tDone."

# Calling macro in xlsm to merge the created csvs into a Excel spreadsheet
Write-Host "Creating Spreadsheet..."
        $workbook = $excel.workbooks.open($excelFile) # Opening workbook
        $worksheet = $workbook.worksheets.item(1) # Selecting worksheet
        $excel.Run("ImportCSVs") # Calling macro
        $workbook.save() #Saving workbook
        $workbook.close() # Closing workbook
$excel.quit() # Closing Excel COM Object
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null # Making sure Excel process is closed.

我还通过COM对象访问Excel VBA脚本,该对象将获取这些CSV并将它们添加到XLSX,每个CSV是一个工作表:

Sub ImportCSVs()
Dim fPath   As String
Dim fCSV    As String
Dim wbCSV   As Workbook
Dim wbMST   As Workbook

Set wbMST = ThisWorkbook
fPath = "C:\temp\group-breakout\"                  'path to CSV files, include the final \
Application.ScreenUpdating = False  'speed up macro
Application.DisplayAlerts = False   'no error messages, take default answers
fCSV = Dir(fPath & "*.csv")         'start the CSV file listing

    On Error Resume Next
    Do While Len(fCSV) > 0
        Set wbCSV = Workbooks.Open(fPath & fCSV)                    'open a CSV file
        wbMST.Sheets(ActiveSheet.Name).Delete                       'delete sheet if it exists
        ActiveSheet.Move After:=wbMST.Sheets(wbMST.Sheets.Count)    'move new sheet into Mstr
        Columns.AutoFit             'clean up display
        fCSV = Dir                  'ready next CSV
    Loop

Worksheets("1-AllGroups").Activate
Worksheets("placeholder").Delete
Workbooks.Application.ActiveWorkbook.SaveAs Filename:="C:\temp\group-breakout\group-breakout.xlsx", FileFormat:=51
Application.ScreenUpdating = True
Set wbCSV = Nothing
End Sub

我遇到的问题是必须在脚本位置包含启用Excel宏的电子表格,以便我可以从脚本中访问它。有没有办法以某种方式将VBA脚本嵌入Powershell脚本并在Excel中运行?或者,或者,直接使用Powershell在VBA脚本中执行任务的方法?

0 个答案:

没有答案
相关问题