카테고리 없음

[엑셀 VBA] 여러 개의 UPC 바코드 한 번에 이미지로 자동 생성하기 (ft. 찌그러짐 완벽 방지)

풀로드 2026. 3. 17. 17:24

✨ 이 매크로의 강력한 핵심 기능

  • 폰트 설치 ❌: 바코드를 아예 이미지로 다운로드하여 엑셀에 박아버립니다. 어느 PC, 어느 환경에서 열어도 100% 동일하게 보입니다.
  • 황금 비율 자동 맞춤: 칸이 좁다고 바코드가 찌그러지지 않습니다. 스캔이 가장 잘 되는 최적의 사이즈(95px)로 고정되고 엑셀 칸 크기가 알아서 맞춰집니다.
  • 셀 종속 (깔끔한 삭제): 바코드 이미지가 셀에 완전히 종속됩니다. 셀 너비를 조절하거나 행을 삭제하면 바코드도 함께 움직이고 깔끔하게 지워집니다.
  • 진행률 팝업 (철벽 방어): 데이터가 많을 때 화면 중앙에 진행률 팝업창이 뜹니다. 이미지가 생성되면서 팝업창을 가리는 버그도 완벽하게 차단했습니다.

💻 바코드 일괄 생성 VBA 코드

아래 코드를 엑셀 VBA 모듈창(Alt + F11 👉 삽입 👉 모듈)에 그대로 복사해서 붙여넣어 주세요

'*****************************************************************
'  troubleshooter
'  2026. 03. 16
'  https://troubleshooter.kr/
'*****************************************************************
Sub GenerateAllBarcodesCustomLocation()
    Dim sourceRange As Range
    Dim targetRange As Range
    Dim currentTarget As Range
    Dim cell As Range
    Dim barcodeURL As String
    Dim shp As Shape
    Dim barcodeText As String
    Dim totalCount As Long
    Dim cellIdx As Long
    Dim validIdx As Long
    Dim progressBox As Shape
    
    On Error Resume Next
    Set sourceRange = Application.InputBox( _
        Prompt:="1. 바코드로 변환할 품번 또는 UPC들을 마우스로 쫙~ 드래그해서 선택하세요." & vbCrLf & "(예: A2부터 A20까지 드래그)", _
        Title:="1단계: 품번 또는 UPC 범위 선택", _
        Type:=8)
    On Error GoTo 0
    If sourceRange Is Nothing Then Exit Sub
    totalCount = sourceRange.Cells.Count
    
    On Error Resume Next
    Set targetRange = Application.InputBox( _
        Prompt:="2. 바코드 그림이 들어갈 '첫 번째 빈 칸'을 마우스로 클릭해 주세요." & vbCrLf & "(이 칸부터 아래로 쭉 생성됩니다.)", _
        Title:="2단계: 바코드 시작 위치 지정", _
        Type:=8)
    On Error GoTo 0
    If targetRange Is Nothing Then Exit Sub
    Set targetRange = targetRange.Cells(1, 1)
    
    ' ⭐️ 화면 중앙 진행률 팝업
    On Error Resume Next
    Set progressBox = ActiveSheet.Shapes.AddShape(msoShapeRectangle, _
        ActiveWindow.VisibleRange.Left + (ActiveWindow.VisibleRange.Width / 2) - 150, _
        ActiveWindow.VisibleRange.Top + (ActiveWindow.VisibleRange.Height / 2) - 50, _
        300, 100)
    On Error GoTo ErrorHandler

    With progressBox
        .Fill.ForeColor.RGB = RGB(0, 120, 215)
        .Line.Visible = msoFalse
        .TextFrame2.VerticalAnchor = msoAnchorMiddle
        .TextFrame2.TextRange.ParagraphFormat.Alignment = msoAlignCenter
        .TextFrame2.TextRange.Font.Fill.ForeColor.RGB = RGB(255, 255, 255)
        .TextFrame2.TextRange.Font.Size = 16
        .TextFrame2.TextRange.Font.Bold = msoTrue
        .TextFrame2.TextRange.Text = "⏳ 준비 중..."
    End With
    DoEvents
    
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    
    cellIdx = 0
    validIdx = 0
    
    For Each cell In sourceRange
        cellIdx = cellIdx + 1
        barcodeText = Trim(cell.Value)
        
        ' 텍스트 업데이트
        progressBox.TextFrame2.TextRange.Text = "[진행중] 바코드 이미지 생성 중...ㅋㅋㅋㅋㅋ" & vbCrLf & vbCrLf & cellIdx & " / " & totalCount & " 개 완료"
        
        ' ==========================================
        ' ⭐️ 핵심 추가: 팝업창을 무조건 '맨 앞으로 가져오기'
        ' ==========================================
        progressBox.ZOrder msoBringToFront
        
        Application.ScreenUpdating = True
        DoEvents
        Application.ScreenUpdating = False
        
        If barcodeText <> "" Then
            Set currentTarget = targetRange.Offset(validIdx, 0)
            
            ' 해상도(scale)는 2로 유지해서 인쇄할 때 깨지지 않게 쨍하게 유지
            barcodeURL = "http://bwipjs-api.metafloor.com/?bcid=code128&text=" & barcodeText & "&includetext&scale=2"
            
            Set shp = Nothing
            On Error Resume Next
            Set shp = ActiveSheet.Shapes.AddPicture(Filename:=barcodeURL, _
                LinkToFile:=msoFalse, SaveWithDocument:=msoTrue, _
                Left:=currentTarget.Left, Top:=currentTarget.Top, _
                Width:=-1, Height:=-1)
            On Error GoTo ErrorHandler
            
            If Not shp Is Nothing Then
                ' 비율은 유지하되, 전체 크기를 예쁘게 다이어트!
                shp.LockAspectRatio = msoTrue ' 찌그러짐 방지 유지
                
                ' 가로 크기를 대폭 축소 (150 -> 95). 세로도 알맞게 쏙 줄어듭니다!
                shp.Width = 95 
                
                ' 엑셀 칸 크기도 다이어트된 바코드에 맞춰서 콤팩트하게 세팅
                currentTarget.RowHeight = shp.Height + 10 ' 위아래 여백 10
                If currentTarget.ColumnWidth < 16 Then
                    currentTarget.ColumnWidth = 16 ' 가로 여백 16 정도면 충분
                End If
                
                ' 정중앙 배치
                shp.Left = currentTarget.Left + ((currentTarget.Width - shp.Width) / 2)
                shp.Top = currentTarget.Top + 5
                
                ' 셀 지우면 같이 지워지게
                shp.Placement = xlMoveAndSize 
            End If
            
            validIdx = validIdx + 1
        End If
    Next cell
    
CleanUp:
    On Error Resume Next
    progressBox.Delete
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    
    MsgBox "총 " & validIdx & "개의 바코드가 생성되었습니다!", vbInformation, "작업 완료"
    Exit Sub
    
ErrorHandler:
    MsgBox "이미지 생성 중 오류가 발생했습니다.", vbCritical, "오류!"
    GoTo CleanUp
End Sub

🚀 초간단 사용 방법

  1. 엑셀 시트에 [삽입] > [도형]으로 예쁜 버튼을 하나 만들어 줍니다.
  2. 버튼을 우클릭하고 **[매크로 지정]**을 눌러 복사해 둔 매크로를 연결합니다.
  3. 버튼을 클릭하면 뜨는 첫 번째 창에서 바코드로 만들 UPC(품번) 목록을 마우스로 쭉 드래그해 줍니다.
  4. 두 번째 창이 뜨면 바코드 이미지가 들어갈 첫 번째 빈 칸을 딱 한 번만 클릭해 줍니다.
  5. 화면 중앙에 파란색 진행률 팝업창이 뜨면서 엑셀이 알아서 일괄 생성을 완료합니다!