Here's an Excel VBA macro that will convert a list of items in column A into an SQL string:
Sub CreateSQLString()
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long
Dim sqlString As String
Dim cellValue As String
' Set the active worksheet
Set ws = ActiveSheet
' Find the last row with data in column A
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
' Check if there's any data
If lastRow < 1 Then
MsgBox "No data found in column A"
Exit Sub
End If
' Start building the SQL string
sqlString = "("
' Loop through each cell in column A
For i = 1 To lastRow
cellValue = Trim(ws.Cells(i, 1).Value)
' Skip empty cells
If cellValue <> "" Then
' Add single quotes around the value and append to SQL string
sqlString = sqlString & "'" & Replace(cellValue, "'", "''") & "'"
' Add comma if not the last item
If i < lastRow Then
sqlString = sqlString & ", "
End If
End If
Next i
' Close the SQL string
sqlString = sqlString & ")"
' Put the result in column C (or display in message box)
ws.Cells(1, 3).Value = sqlString
' Also copy to clipboard
Dim dataObj As Object
Set dataObj = CreateObject("MSForms.DataObject")
dataObj.SetText sqlString
dataObj.PutInClipboard
MsgBox "SQL string created in cell C1 and copied to clipboard!" & vbNewLine & vbNewLine & sqlString
End Sub
This macro will:
- Read all values from column A
- Convert them into a properly formatted SQL IN clause format like
('item1', 'item2', 'item3')
- Handle single quotes in the data by escaping them
- Skip empty cells
- Place the result in cell C1
- Copy the result to your clipboard
- Show a message box with the result
To use this macro:
- Press Alt+F11 to open the VBA editor
- Insert a new module (Insert > Module)
- Paste this code
- Close the VBA editor
- Run the macro by pressing Alt+F8, selecting "CreateSQLString", and clicking Run
The result will be formatted for use in SQL WHERE clauses like: WHERE column_name IN ('value1', 'value2', 'value3')