郵便番号のデータベースを作成
郵便番号のデータベースを作成してみましょう。
これは、次に紹介する住所から郵便番号に変換するマクロの前準備です。
元データは日本郵便のホームページからダウンロードします。
「全国一括」をダウンロードしてください。
ダウンロードしたCSVは、1,000,000 行以上あるので、Input関数を使用して
読み込んでいます。
INSERT文は使用しないで、DB_Record.AddNew で時間を短縮しています。
詳しくは説明しませんが、サンプル をダウンロードして動かしてみてください。
Public Const ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
Sub Create_ZipMDB()
Dim DB_Catalog As ADOX.Catalog
Dim DB_Connect As ADODB.Connection
Dim DB_Cmd As ADODB.Command
Dim FileSystemOBJ As Object
Dim MDB_FolderPath As String
Const DB_Name = "郵便番号.mdb"
MDB_FolderPath = FolderPath
Set FileSystemOBJ = CreateObject("Scripting.FileSystemObject")
If FileSystemOBJ.FileExists(MDB_FolderPath & "\" & DB_Name) Then
FileSystemOBJ.DeleteFile MDB_FolderPath & "\" & DB_Name
End If
Set FileSystemOBJ = Nothing
Set DB_Catalog = New ADOX.Catalog
DB_Catalog.Create ConnectionString & MDB_FolderPath & "\" & DB_Name & ";"
Set DB_Catalog = Nothing
Set DB_Connect = New ADODB.Connection
DB_Connect.Open ConnectionString & MDB_FolderPath & "\" & DB_Name & ";"
Set DB_Cmd = New ADODB.Command
DB_Cmd.ActiveConnection = DB_Connect
DB_Cmd.CommandText = "DROP TABLE Zip_Code"
On Error Resume Next
DB_Cmd.Execute
On Error GoTo 0
DB_Cmd.ActiveConnection = DB_Connect
DB_Cmd.CommandText = "CREATE TABLE Zip_Code (" & _
"CODE1 INTEGER ," & _
"ZIP_OLD TEXT(5)," & _
"ZIPCODE TEXT(7)," & _
"KEN_KANA TEXT(50)," & _
"SHI_KANA TEXT(50)," & _
"CHO_KANA TEXT(100)," & _
"KEN_KANJI TEXT(50)," & _
"SHI_KANJI TEXT(50)," & _
"CHO_KANJI TEXT(100)," & _
"FLG1 INTEGER," & _
"FLG2 INTEGER," & _
"FLG3 INTEGER," & _
"FLG4 INTEGER," & _
"FLG5 INTEGER," & _
"FLG6 INTEGER )"
DB_Cmd.Execute
Set DB_Cmd = Nothing
DB_Connect.Close
Set DB_Connect = Nothing
End Sub
Sub Insert_Zip()
Dim DB_Connect As ADODB.Connection
Dim DB_Record As ADODB.Recordset
Dim FieldList As Variant
Dim ZipData(14) As Variant
Dim File種類 As String
Dim Prompt As String
Dim FileNamePath As Variant
Dim MDB_Path As String
Dim ch1 As Long
File種類 = "CSV ファイル (*.CSV),*.CSV"
Prompt = "郵便番号データファイル CSV (全国一括)を選択してください"
FileNamePath = Application.GetOpenFilename(File種類, , Prompt)
If FileNamePath = False Then
End
End If
File種類 = "mdb (*.mdb),*mdb"
Prompt = "郵便番号.mdb を選択してください。"
MDB_Path = Application.GetOpenFilename(File種類, , Prompt)
ch1 = FreeFile
Open FileNamePath For Input As #ch1
Set DB_Connect = New ADODB.Connection
DB_Connect.Open ConnectionString & MDB_Path & ";"
Set DB_Record = New ADODB.Recordset
DB_Record.Open "Zip_Code", DB_Connect, adOpenForwardOnly, adLockOptimistic
FieldList = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
Do Until EOF(ch1)
Input #ch1, ZipData(0), ZipData(1), ZipData(2), ZipData(3), ZipData(4), _
ZipData(5), ZipData(6), ZipData(7), ZipData(8), ZipData(9), _
ZipData(10), ZipData(11), ZipData(12), ZipData(13), ZipData(14)
DB_Record.AddNew FieldList, ZipData
Loop
Close #ch1
DB_Record.Close
Set DB_Record = Nothing
DB_Connect.Close
Set DB_Connect = Nothing
End Sub