How To Validate Excel Column Headers Prior To Importing Into A Database (VBA Code)
I have an Excel VBA Macro to upload data into a SQL Server database. The tutorial can be found here. I wanted to add an extra step:
Validate column headers in Excel before uploading the data
The problem was that if the source file changed, I needed a notification that the data was in the wrong format.
The trick is to perform this validation first
Here’s the code:
The function is on lines 13–25 and returns a Boolean (true/false).
Line 18 will find a specific Cell and check the value. Here, I named the worksheet “import”. The cell is a variable based on a column (defined on Line 1) as is the header for the row (Line 2).
If the cell (here, “A2”) isn’t the expected value, then an alert is given (Line 19) and the function returns false.
Copy the code block on lines 18–21 for each column header you want to check
The code on Lines 4–9 is what is run to call the function.
By having this validation in place- and running it before the actual import process happens- it can save time if the source file unexpectedly changes format.