Vous êtes sur la page 1sur 1

Option Explicit

'-------------------------------------------------------------------------------------' Module
: Mdulo1
' Author
: MVP Sergio Alejandro Campos
' Date
: 23/06/2013
' Purpose : Generar Query de SQL INSERT INTO
' Website : http://blogs.itpro.es/exceleinfo
'-------------------------------------------------------------------------------------'
Sub GenerarInsertInto()
'Definiendo variables
Dim Filas As Integer
Dim Cuenta As Integer
Dim Rango As String
Dim Celda As Range
Dim Valor, Valor1, Valor2 As String
Dim Largo As Integer
Dim RowCursor As Integer
Dim strSQL As String
Dim Mensaje As String
'
On Error GoTo Errores
Filas = Application.WorksheetFunction.CountA(Range("A:A"))
Cuenta = 1
Rango = Application.Transpose(ActiveCell.CurrentRegion.Resize(1).Select)
'
'Extrayendo encabezados
For Each Celda In Selection
Valor = Celda.Value
Valor1 = Valor1 & Valor & ", "
Next Celda
Largo = Len(Valor1)
Valor2 = Left(Valor1, Largo - 2)
'
'Generando Query
With ActiveWorkbook.Sheets("Datos")
For RowCursor = 2 To Filas
strSQL = "INSERT INTO Tabla (" & Valor2 & ") " & _
"VALUES ('" & .Cells(RowCursor, 1) & "', " & _
"'" & .Cells(RowCursor, 2) & "', " & _
.Cells(RowCursor, 3) & "," & _
"'" & .Cells(RowCursor, 4) & "', " & _
"'" & .Cells(RowCursor, 5) & "')"
Sheets("Query INSERT INTO").Range("A" & Cuenta).Value = strSQL
Cuenta = Cuenta + 1
Next
End With
'
Mensaje = MsgBox("Query generada. Deseas ver el cdigo generado?", vbQuestion + vb
YesNo)
If Mensaje = vbYes Then Sheets("Query INSERT INTO").Activate
'
'Manejo de errores
Exit Sub
Errores:
MsgBox "Error: " & Err.Description, vbExclamation, "EXCELeINFO"
End Sub