아래는 엑셀 스키마를 기반으로 데이터 검증을 수행하는 VBA 스크립트입니다. 각 열에 대해 데이터 유형, 필수 여부, 최대 길이 등을 검사합니다. 필요에 맞게 확장할 수 있습니다.
Sub ValidateData()
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long
Dim errorMsg As String
' 데이터가 있는 워크시트 설정
Set ws = ThisWorkbook.Sheets("Data") ' 데이터 시트 이름
' 마지막 데이터 행 찾기
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
errorMsg = ""
' 데이터 검증 루프
For i = 2 To lastRow ' 2번째 행부터 시작 (헤더 제외)
Dim id As String
Dim name As String
Dim age As String
Dim email As String
Dim regDate As String
' 데이터 읽기
id = ws.Cells(i, 1).Value
name = ws.Cells(i, 2).Value
age = ws.Cells(i, 3).Value
email = ws.Cells(i, 4).Value
regDate = ws.Cells(i, 5).Value
' ID 검증 (숫자, 필수)
If Not IsNumeric(id) Or id = "" Then
errorMsg = errorMsg & "Row " & i & ": ID must be a numeric value and cannot be empty." & vbNewLine
End If
' 이름 검증 (문자열, 필수, 최대 50자)
If Len(name) = 0 Then
errorMsg = errorMsg & "Row " & i & ": Name is required." & vbNewLine
ElseIf Len(name) > 50 Then
errorMsg = errorMsg & "Row " & i & ": Name exceeds the maximum length of 50 characters." & vbNewLine
End If
' 나이 검증 (숫자, 선택, 0-120)
If age <> "" Then
If Not IsNumeric(age) Or Val(age) < 0 Or Val(age) > 120 Then
errorMsg = errorMsg & "Row " & i & ": Age must be a numeric value between 0 and 120." & vbNewLine
End If
End If
' 이메일 검증 (필수, 이메일 형식)
If Len(email) = 0 Then
errorMsg = errorMsg & "Row " & i & ": Email is required." & vbNewLine
ElseIf Not email Like "*@*.*" Then
errorMsg = errorMsg & "Row " & i & ": Email format is invalid." & vbNewLine
End If
' 등록일 검증 (필수, 날짜 형식)
If Not IsDate(regDate) Then
errorMsg = errorMsg & "Row " & i & ": Registration Date must be a valid date." & vbNewLine
End If
Next i
' 결과 출력
If errorMsg = "" Then
MsgBox "Data validation completed successfully. No errors found.", vbInformation
Else
MsgBox "Data validation completed with errors:" & vbNewLine & errorMsg, vbExclamation
End If
End Sub
설명
- ws.Cells(i, 1).Value 등으로 각 컬럼 값을 읽습니다.
- IsNumeric(), Len(), IsDate() 등을 사용해 데이터 타입 및 조건을 검증합니다.
- 오류 메시지가 발견되면 사용자에게 메시지 박스로 출력합니다.
사용 방법
- 엑셀 파일에서 ALT + F11을 눌러 VBA 편집기를 엽니다.
- 새 모듈을 추가하고 위 코드를 붙여넣습니다.
- 데이터를 담은 시트를 "Data"로 이름 지정합니다.
- ALT + F8을 눌러 ValidateData 매크로를 실행합니다.
필요한 추가 검증 로직이나 조건이 있으면 알려주세요!
'Excel을 활용한 알고리즘 개발' 카테고리의 다른 글
[Excel을 활용한 알고리즘 개발] 함수와 루틴 선언 및 호출 (0) | 2025.03.21 |
---|---|
[Excel을 활용한 알고리즘 개발] VBA Script 특징 및 개요 2 (0) | 2025.03.21 |
[Excel을 활용한 알고리즘 개발] 엑셀 히스토리 테이블 데이터 시트 (0) | 2025.02.09 |
[Excel을 활용한 알고리즘 개발] Excel 유용한 통계 함수 목록 (1) | 2025.02.09 |
[Excel을 활용한 알고리즘 개발] Excel 통계 테이블 생성을 위한 데이터시트 (0) | 2025.02.09 |