컴퓨터/엑셀

vba image 함수

풍경소리^^ 2024. 12. 15. 18:51
Function IMAGE(urlCell As Range) As String
    Dim imgURL As String
    Dim targetCell As Range
    Dim imgShape As shape
    Dim ws As Worksheet
    Dim imgWidth As Double
    Dim imgHeight As Double
    Dim cellWidth As Double
    Dim cellHeight As Double
    Dim scaleFactor As Double
    Dim imgLeft As Double
    Dim imgTop As Double

    On Error GoTo ErrorHandler
    
    Application.Volatile True

    ' URL이 있는 셀의 값을 가져오기
    imgURL = urlCell.Value

    ' URL이 있는 셀이 위치한 워크시트 및 셀 설정
    Set ws = urlCell.Worksheet
    Set targetCell = Application.Caller ' 함수를 호출한 셀을 타겟 셀로 설정

    ' 이미지 크기를 조정하기 위한 셀 크기 가져오기
    cellWidth = targetCell.Width
    cellHeight = targetCell.Height

    ' 이미지를 삽입할 위치 지정 및 크기 조정
    Set imgShape = ws.Shapes.AddPicture(imgURL, _
                                        msoFalse, msoCTrue, _
                                        0, 0, -1, -1) ' 임시로 원본 크기로 삽입
'    매개변수 설명
'    Filename (필수): 삽입할 그림 파일의 경로를 문자열로 지정합니다.
'
'    예: "C:\Images\example.jpg"
'    LinkToFile (필수): 그림 파일을 문서에 링크로 삽입할지 여부를 결정합니다.
'
'    MsoTriState.msoTrue: 그림 파일에 대한 링크를 유지합니다.
'    MsoTriState.msoFalse: 그림 파일을 문서에 포함합니다.
'    SaveWithDocument (필수): 문서 저장 시 그림을 함께 저장할지 여부를 결정합니다.
'
'    MsoTriState.msoTrue: 문서에 그림 파일을 포함하여 저장합니다.
'    MsoTriState.msoFalse: 문서에 그림을 포함하지 않고 저장합니다.
'    Left (필수): 그림의 왼쪽 위치를 포인트 단위로 지정합니다.
'
'    Top (필수): 그림의 위쪽 위치를 포인트 단위로 지정합니다.
'
'    Width (필수): 그림의 너비를 포인트 단위로 지정합니다.
'
'    Height (필수): 그림의 높이를 포인트 단위로 지정합니다.

    ' 원본 비율로 셀 크기에 맞게 이미지 크기 조정
    imgWidth = imgShape.Width
    imgHeight = imgShape.Height

    ' 너비와 높이 중 작은 비율로 맞추기
    If (cellWidth / imgWidth) < (cellHeight / imgHeight) Then
        scaleFactor = cellWidth / imgWidth
    Else
        scaleFactor = cellHeight / imgHeight
    End If
    
    ' 크기를 줄이는 비율 적용 (예: 90%)
    scaleFactor = scaleFactor * 0.9

    imgShape.LockAspectRatio = msoTrue
    imgShape.Width = imgWidth * scaleFactor
    imgShape.Height = imgHeight * scaleFactor

    ' 이미지를 셀의 가운데에 위치시키기
    imgLeft = targetCell.Left + (cellWidth - imgShape.Width) / 2
    imgTop = targetCell.Top + (cellHeight - imgShape.Height) / 2
    imgShape.Left = imgLeft
    imgShape.Top = imgTop
    
    

    'IMAGE = "Image inserted successfully"
    Exit Function

ErrorHandler:
    IMAGE = "Error: " & Err.Description
End Function

image.xls
2.20MB