从Powershell内执行Excel VBA宏,因为宏内的循环不起作用

时间:2019-09-10 11:25:57

标签: excel vba powershell

我正在尝试从Powershell中执行Excel VBA宏。 在宏内部,我使用for循环删除excel单元格内的一些错误值。
循环不是由powershell执行的,但是如果我在VBA编辑器中运行宏,它将运行正常。

请在下面找到我的代码:


Powershell中的代码:

$excel = New-Object -Com Excel.Application                                   $objMisVal = [System.Reflection.Missing]::Value                                                                                                           
$xlsdoc = "C:\Path\ExcelFile.xlsm"
$sheetname = "XXX"
$makro = "formatanpassungen"                       
$workbook = $excel.workbooks.open($xlsdoc, $objMisVal, $objMisVal, $objMisVal, `
$objMisVal, $objMisVal, $objMisVal, $objMisVal, $objMisVal, $objMisVal, `
$objMisVal, $objMisVal, $objMisVal, $objMisVal, $objMisVal)                                   

$excel.visible = $true

$excel.run($makro)                                 

$Workbook|Get-Member *Save*
$workbook.Save()

Excel VBA中的代码:

Sub formatanpassungen()
Dim iZeile As Integer
Dim sRechnungsNrOLD As String
Dim sRechnungsNrNEW As String

'ganzes Arbeitsblatt nach doppelten Rechnungsnummern durchsuchen
For i = 4 To iZeile

    If Sheets("XXX").Cells(i, 9) = 0 Then GoTo 10

    'Ermittlung RG-Nr OLD
    If i >= 5 Then sRechnungsNrOLD = Sheets("XXX").Cells(i - 1, 9)

    'Ermittlung RG-Nr NEW
    sRechnungsNrNEW = Sheets("XXX").Cells(i, 9)

    'Wenn RG-NrNEW = RG-NrOLD, then....
    If sRechnungsNrNEW = sRechnungsNrOLD Then
        Sheets("XXX").Cells(i, 14) = ""
        Sheets("XXX").Cells(i, 15) = ""
    End If

10:

Next i
End Sub

1 个答案:

答案 0 :(得分:0)

下面的代码现在可以正常运行,但不能运行完整的代码。

' Aktualisieren Makro

Dim iZeile As Integer
Dim sRechnungsNrOLD As String
Dim sRechnungsNrNEW As String

iZeile = ActiveSheet.Cells(Rows.Count, 7).End(xlUp).Row

With Range("I4:I" & iZeile)
    .NumberFormat = "General"
    .Value = .Value
End With

'Formatanpassungen
iZeile = ActiveSheet.Cells(Rows.Count, 7).End(xlUp).Row
For i = 4 To iZeile

    If Sheets("xxx").Cells(i, 9) = 0 Then GoTo 10

    'Ermittlung RG-Nr OLD
    If i >= 5 Then sRechnungsNrOLD = Sheets("xxx").Cells(i - 1, 9)

    'Ermittlung RG-Nr NEW
    sRechnungsNrNEW = Sheets("xxx").Cells(i, 9)

    'Wenn RG-NrNEW = RG-NrOLD, dann....
    If sRechnungsNrNEW = sRechnungsNrOLD Then
        Sheets("xxx").Cells(i, 14) = ""
        Sheets("xxx").Cells(i, 15) = ""
    End If

10:

Next i

'Alle Pivot-Tabellen aktualisieren
Sheets("ÜBERSICHT_Alle").Select
Range("A7").Select
ActiveWorkbook.RefreshAll
Sheets("xxx").Select

End Sub