이제 PowerShell에서 VBA를 수행하도록 하겠습니다.

6842 단어 tech

PowerShell에서 VBA 수행


Windows와 응용 프로그램을 설치할 수 없는 환경에서는 Excel 파일을 기계적으로 처리하고 좋은 방법을 찾을 때의 노트가 필요하다.잊어버릴 것 같으니까 기사부터 써주세요.

PowerShell에서 Excel로


지금 엑셀을 조종하려면하지만 PowerShell에서 COM 인터페이스를 사용하면 같은 일을 할 수 있을 것 같습니다.그리고 비교적 간단하다.

셀 값 읽기


하고 싶은 일은 칸의 값을 읽어라.그게 다야.
지정하지 않으면 백그라운드에서 Excel이 계속 시작되므로 주의해야 합니다.나중에 VS코드에서 실행하면 백그라운드의 Excel이 끝나지 않을 거야...왜 그랬을까?
image.png
read.ps1
$file = "read.xlsx"
$excel = $null

try {
    $excel = New-Object -ComObject Excel.Application
    $book = $excel.Workbooks.Open($file)
    $sheet = $book.ActiveSheet

    echo $sheet.Cells(1,2).Text
    echo $sheet.Cells(1,3).Text

    $book.Close()
} finally {
    $excel.Quit()
    [System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($excel) | Out-Null
    [System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($book) | Out-Null
}
실행해봐.
PS> powershell -NoProfile -ExecutionPolicy Unrestricted .\read.ps1

매크로 실행


Excel에서 매크로를 실행할 수도 있습니다.데이터를 가져와서 업데이트하고 pitto를 저장할 수 있다면 필요 없어요FinalReleaseComObject!!
macro.xlsm
Sub Hello()
  MsgBox "Hello, World!"
End Sub
의 Excel 매크로를 PowerShell에서 호출해 봅니다.
macro.ps1
$file = "macro.xlsm"
$excel = $null

try {
    $excel = New-Object -ComObject Excel.Application
    $book = $excel.Workbooks.Open($file)

#    $target = "Module1.Hello"   # こっちでもいける
    $target = "Hello"
    $excel.Run($target)

    $book.Close()
} finally {
    $excel.Quit()
    [System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($excel) | Out-Null
    [System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($book) | Out-Null
}
실행해봐.
PS> powershell -NoProfile -ExecutionPolicy Unrestricted .\macro.ps1

그 외에도 방법이 있다


이렇게 간단한 일이 자바지고의 생각이 아니라면 다양한 수단이 있을 것이다.

참고 자료


PowerShell에서 Excel 작업(자동)
Windows PowerShell을 사용한 Excel 작업 – 셀 작업 편vol.1
Office 애플리케이션의 제어는 PowerShell입니까 아니면 VBA입니까?

좋은 웹페이지 즐겨찾기