I am in the process of creating a database of County information, and I needed to insert several thousand records. I was able to get the data into Excel, but now I needed to write an SQL Insert statement to get the records into my database. SQL wizards, I’m sure you know a more efficient way to write this INSERT. Actually, what is generated is a series of INSERT statements. If you’d like to share your knowledge, please leave a comment, and I’d gladly update the macro for your improved format.
How it works:
Let’s start by looking at my spreadsheet:
- I’m using Row 1 as my header.
- The values are: state, county, statefips, countyfips, and fipsclass
- Beginning on row 2 I list that information.
- Columns A, B and E are text.
- Columns C and D are Integers. ***Note this in the macro when modifying.***
Upon running the macro, it will ask for the start row. Enter the number for the row that begins your data.
It then loops through columns A through E and puts those values into variables.
Then, it writes the insert statement, with our variables included, to the file specified by the “MyFile” variable. Currently, it will be written to the active/default Excel directory.
The macro will then loop down all of the rows until it finds a blank.
This macro is fairly short, so I’m copying it below.
I just realized that there are several things I could change to optimize this code and make it more useful. I’ll try to get an update out soon. Until then, what would YOU change in this code?
Sub generateInsert()
Dim state As String
Dim county As String
Dim statefips As Integer
Dim countyfips As Integer
Dim fipsclass As String
Dim myRow As Integer
Dim myCol As IntegermyRow = InputBox(“What row to START on?”)
myCol = 1
MyFile = “insertStmt.txt”‘set and open file for output
fnum = FreeFile()
Open MyFile For Output As fnumDo Until ActiveSheet.Cells(myRow, myCol) = “” ‘Loop until you find a blank.
state = ActiveSheet.Cells(myRow, myCol)
myCol = myCol + 1
county = ActiveSheet.Cells(myRow, myCol)
myCol = myCol + 1
statefips = ActiveSheet.Cells(myRow, myCol)
myCol = myCol + 1
countyfips = ActiveSheet.Cells(myRow, myCol)
myCol = myCol + 1
fipsclass = ActiveSheet.Cells(myRow, myCol)myCol = 1 ‘ Return to column A
myRow = myRow + 1 ‘ Move down 1 rowPrint #fnum, “insert into countyTable (state, county, statefips, countyfips, fipsclass)”
Print #fnum, “values (‘” & state & “‘, ‘” & county & “‘,” & statefips & “, ” & countyfips & “, ‘” & fipsclass & “‘);”Loop
‘ Close the file
Close #fnumEnd Sub
I’m looking forward to your comments.
– Jason
Leave a Reply