0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

スクリーンショット(画面キャプチャ)を保存するVBAコード

Posted at
ScreenShotModule.bas
Option Explicit

Public Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, _
                                                    ByVal bScan As Byte, _
                                                    ByVal dwFlags As Long, _
                                                    ByVal dwExtraInfo As Long)

Const ALT_KEY = &HA4            '//[Alt]キー
Const PRINT_SCRN_KEY = &H2C     '//[PrintScrn]キー
Const KEY_DOWN = &H1            '// キーを押す
Const KEY_UP = &H2              '// キーを放す
'// クリップボードの画像を保存する

Sub SaveScreenShot(ByVal save_folder_path As String, _
                    ByVal img_file_name As String, _
                    ByVal img_type As String, _
                    Optional ByVal alt As Boolean)

'    save_folder_path[画像の保存先フォルダパス](例:C:\temp\Images)
'    img_file_name   [画像のファイル名]        (例:hoge.png)
'    img_type        [画像フォーマット]        (png、jpg、bmpなど)
'    alt             [Altキーを押すかどうか]   (アクティブウィンドウのみキャプチャするかどうか)

    Dim psCmdStr    As String   '// PowerShellコマンド
    Dim imgFilePath As String   '// 画像のフルパス

    imgFilePath = CreateObject("Scripting.FileSystemObject").BuildPath(save_folder_path, img_file_name)

    '//[Alt]キーを押す(アクティブウィンドウをキャプチャする場合)
    If alt Then keybd_event ALT_KEY, 0, KEY_DOWN, 0

    '//[PrintScrn]キーを押す
    keybd_event PRINT_SCRN_KEY, 0, KEY_DOWN, 0

    '//[PrintScrn]キーを放す
    keybd_event PRINT_SCRN_KEY, 0, KEY_DOWN Or KEY_UP, 0

    '//[Alt]キーを放す(アクティブウィンドウをキャプチャする場合)
    If alt Then keybd_event ALT_KEY, 0, KEY_DOWN Or KEY_UP, 0

    '// PowerShellのクリップボード画像保存コマンド
    psCmdStr = "powershell Add-Type -AssemblyName System.Windows.Forms;$ImagePath = '" & imgFilePath & _
               "';  [Windows.Forms.Clipboard]::GetImage().Save($ImagePath, [System.Drawing.Imaging.ImageFormat]::" & _
               img_type & ")"

    '// PowerShellコマンド実行
    CreateObject("WScript.Shell").Run Command:=psCmdStr, WindowStyle:=0, WaitOnReturn:=True

End Sub
Sub test1()

    Dim saveFolderPath  As String
    Dim imgFileName     As String
    Dim imgType         As String

    saveFolderPath = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%USERPROFILE%") & "\Downloads"
    imgFileName = "hoge.png"
    imgType = "png"

    Call SaveScreenShot(saveFolderPath, imgFileName, imgType, True)

End Sub

参照サイト:
Excel VBA を学ぶなら moug モーグ | 即効テクニック | 画面をキャプチャする
Excelマクロでスクショを取る - 技術関連の覚書
クリップボードの画像を保存する方法!マクロで簡単実装! - エク短|Extan.jp

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?