VBAオジサンのらくがき帳

郵便番号検索

2021-07-22 00:00:00

郵便局のダウンロードデータを使って郵便番号から住所、住所から郵便番号を検索するコードを作成してみた。

Sub PostCodeToAddress(postCode As String)
    Dim buf As String
    Dim fileNum As Integer
    Dim fileName As String

    fileName = ThisWorkbook.Path & "\KEN_ALL.CSV"
    fileNum = FreeFile
    Open fileName For Input As #fileNum

    Dim i As Long
    Dim s As Variant
    i = 1
    Do Until EOF(fileNum)
        Line Input #fileNum, buf
        If postCode = Mid(buf, 16, 7) Then
            s = Split(buf, ",")
            Debug.Print Replace(s(6) & s(7) & s(8), """", "")
            Exit Do
        End If
        i = i + 1
    Loop
    Close #fileNum
End Sub

Sub AddressToPostCode(address As String)
    Dim buf As String
    Dim fileNum As Integer
    Dim fileName As String

    fileName = ThisWorkbook.Path & "\KEN_ALL.CSV"
    fileNum = FreeFile
    Open fileName For Input As #fileNum

    Dim i As Long
    Dim s As Variant
    i = 1
    Do Until EOF(fileNum)
        Line Input #fileNum, buf
        s = Split(buf, ",")
        If InStr(1, Replace(s(6) & s(7) & s(8), """", ""), address) > 0 Then
            Debug.Print Replace("〒" & s(2) & " " & s(6) & s(7) & s(8), """", "")
        End If
        i = i + 1
    Loop
    Close #fileNum
End Sub

元データはこちらからダウンロードできます。

https://www.post.japanpost.jp/zipcode/download.html