【Excel VBA】画像ファイルのサイズ(横x縦)を取得する方法

スポンサーリンク

Excel VBAで画像ファイルのサイズ(横x縦)を取得する方法を説明してきます。

画像ファイルのサイズを取得するコード

画像ファイルのサイズを取得するコードです。

対応形式は「PNG,JPEG,GIF,TIFF,SVG」です。

''' <summary>
''' 画像ファイルのサイズ(横x縦)を取得する
''' </summary>
''' <param name="inPath">”参照先パス(必須)</param>
''' <param name="tmpSh">図形の出力先シート</param>
''' <returns>画像サイズ</returns>
Function ImgFileSizeGet(ByVal inPath As String, Optional ByRef tmpSh As Worksheet) As Collection
    '画像を図形に変換する
    If tmpSh Is Nothing Then Set tmpSh = ActiveSheet
    Dim shp As Shape: Set shp = tmpSh.Shapes.AddPicture(inPath, msoFalse, msoTrue, 1, 1, -1, -1)
    With shp
        '図形サイズをpxに変換
        Set ImgFileSizeGet = New Collection
        ImgFileSizeGet.Add .Width / 0.75, "Width"
        ImgFileSizeGet.Add .Height / 0.75, "Height"
        '図形を削除
        .Delete
    End With
End Function

使用例

Excelファイル直下の「test.png」の画像サイズを取得するサンプルです。

Private Sub Sample()
     Dim rtn As Collection: Set rtn = ImgFileSizeGet(ThisWorkbook.Path & "\test.png")
     MsgBox rtn("Width") & "*" & rtn("Height")
End Sub
タイトルとURLをコピーしました