Conexion a hoja con variable usando sql
Buenas con todos los expertos y demas usuarios, pero que em puedan ayudar,
veran tengo una conexion a una hoja donde directamente pongo la hoja a la me voy a conectar, pero hay muc has hojas entonces mi pregunta es se puede colocar una variable que escribo selecciono en combobox y asi hacer la conexcion a la hoja seleccionada, yo ya he cargado a un combobox las hojas de ese libro. Porque una vez seleccionada la hoja en el combo me tiene que mostrar en un flexgrid los datos de esa hoja .
este codigo es del modulo actualmente:
Sub Conectar()
Application.ScreenUpdating = FalseDim UltFila As Long, NombreHoja As String, Maq As StringDim Fila As Long, Columna As Long
Cnx.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & _ ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
Tracto11.SelectNombreHoja = Tracto11.NameUltFila = Tracto11.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).RowSet Rst = New ADODB.RecordsetWith Rst .ActiveConnection = Cnx .CursorType = adOpenStatic .CursorLocation = adUseClient .LockType = 3 'adLockBatchOptimisticEnd With
End Sub
este el codigo esta en change del combobox (PERO CON LA HOJA YA ASIGNADA)
Private Sub cbcodigo_Change()
Application.ScreenUpdating = FalseCall ConectarDim Consulta As String, NombreHoja As String, UltFila As Long, Fila As Long, Columna As LongTracto11.SelectNombreHoja = Tracto11.NameUltFila = Tracto11.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).RowConsulta = "SELECT * FROM [" & NombreHoja & "$C11:L" & UltFila & "]"Rst.Open Consulta, Cnx
If Rst.RecordCount = 0 Then MsgBox "No Registrado", 64, "" MSHFlexGrid1.Clear Rst.Close Cnx.Close Set Rst = Nothing Set Cnx = Nothing Exit SubEnd If ' -- Configurar el Grid With MSHFlexGrid1 ' -- Deshabilitar el repintado del control ( Para que la carga sea mas veloz ) .Redraw = False ' -- Seleccionar registros del Grid por Fila .SelectionMode = flexSelectionByRow ' -- Cantidad de filas inicial .Rows = 9 ' -- Modo de encabezados .FixedRows = 1 .FixedCols = 0 ' -- Cantidad de filas y columnas .Rows = 1 .Cols = Rst.Fields.Count ' -- Redimensionar el Array a la cantidad de campos de la tabla ReDim Ancho_Columna(0 To Rst.Fields.Count - 1)
Fila = 1 ' -- Recorrer todos los registros del recordset Rst.MoveFirst Do While Not Rst.EOF .Rows = .Rows + 1 ' Añade una nueva fila For Columna = 0 To Rst.Fields.Count - 1 ' -- Combobar que el valor no es nulo If Not IsNull(Rst.Fields(Columna).Value) Then ' -- Agrega el registro en la fila y columna específica .TextMatrix(Fila, Columna) = Rst.Fields(Columna).Value End If Next ' -- Siguiente registro Rst.MoveNext Fila = Fila + 1 'Incrementa la fila Loop ' -- Cierra el recordset y la conexión abierta .FormatString = "FECHA|HOROMETRO|DIESEL|ACEITE DE MOTOR|FILTRO DE ACEITE|FILTRO DE PETROLEO|SEPARADOR DE AGUA|ACEITE TRANSMISION|ACEITE HIDRAULICO|OBSERVACIONES" .ColWidth(0) = 1000 .ColWidth(1) = 1000 .ColWidth(2) = 1200 .ColWidth(3) = 1200 .ColWidth(4) = 1200 .ColWidth(5) = 1200 .ColWidth(6) = 1200 .ColWidth(7) = 1200 .ColWidth(8) = 1500 .ColWidth(9) = 1500 Rst.Close Cnx.Close Set Rst = Nothing Set Cnx = Nothing ' -- Establece los ancho de columna de la grilla ' -- Volver a Habilitar el repintado del Grid .Redraw = True
End WithOn Error GoTo mensaje
Sheets("Datos").Activate Range("A1").Select Cells.Find(What:=UCase(cbcodigo), After:=ActiveCell, LookIn:=xlValues, LookAt:= _ xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _ False).Activate TXTSERIE = ActiveCell.Offset(0, 2).Value TXTDSC = ActiveCell.Offset(0, 1).Value
Exit Submensaje:
MsgBox "No se encontraron registros", vbInformation, "MENSAJE" Application.ScreenUpdating = True
End Sub
Lo que busco es que al seleccionar en el combo box asigne al hoja respectibva para las consultas. No se si sera posible subir el archivo??
espero me puedan ayudar
Saludos
Oguerrero81
veran tengo una conexion a una hoja donde directamente pongo la hoja a la me voy a conectar, pero hay muc has hojas entonces mi pregunta es se puede colocar una variable que escribo selecciono en combobox y asi hacer la conexcion a la hoja seleccionada, yo ya he cargado a un combobox las hojas de ese libro. Porque una vez seleccionada la hoja en el combo me tiene que mostrar en un flexgrid los datos de esa hoja .
este codigo es del modulo actualmente:
Sub Conectar()
Application.ScreenUpdating = FalseDim UltFila As Long, NombreHoja As String, Maq As StringDim Fila As Long, Columna As Long
Cnx.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & _ ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
Tracto11.SelectNombreHoja = Tracto11.NameUltFila = Tracto11.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).RowSet Rst = New ADODB.RecordsetWith Rst .ActiveConnection = Cnx .CursorType = adOpenStatic .CursorLocation = adUseClient .LockType = 3 'adLockBatchOptimisticEnd With
End Sub
este el codigo esta en change del combobox (PERO CON LA HOJA YA ASIGNADA)
Private Sub cbcodigo_Change()
Application.ScreenUpdating = FalseCall ConectarDim Consulta As String, NombreHoja As String, UltFila As Long, Fila As Long, Columna As LongTracto11.SelectNombreHoja = Tracto11.NameUltFila = Tracto11.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).RowConsulta = "SELECT * FROM [" & NombreHoja & "$C11:L" & UltFila & "]"Rst.Open Consulta, Cnx
If Rst.RecordCount = 0 Then MsgBox "No Registrado", 64, "" MSHFlexGrid1.Clear Rst.Close Cnx.Close Set Rst = Nothing Set Cnx = Nothing Exit SubEnd If ' -- Configurar el Grid With MSHFlexGrid1 ' -- Deshabilitar el repintado del control ( Para que la carga sea mas veloz ) .Redraw = False ' -- Seleccionar registros del Grid por Fila .SelectionMode = flexSelectionByRow ' -- Cantidad de filas inicial .Rows = 9 ' -- Modo de encabezados .FixedRows = 1 .FixedCols = 0 ' -- Cantidad de filas y columnas .Rows = 1 .Cols = Rst.Fields.Count ' -- Redimensionar el Array a la cantidad de campos de la tabla ReDim Ancho_Columna(0 To Rst.Fields.Count - 1)
Fila = 1 ' -- Recorrer todos los registros del recordset Rst.MoveFirst Do While Not Rst.EOF .Rows = .Rows + 1 ' Añade una nueva fila For Columna = 0 To Rst.Fields.Count - 1 ' -- Combobar que el valor no es nulo If Not IsNull(Rst.Fields(Columna).Value) Then ' -- Agrega el registro en la fila y columna específica .TextMatrix(Fila, Columna) = Rst.Fields(Columna).Value End If Next ' -- Siguiente registro Rst.MoveNext Fila = Fila + 1 'Incrementa la fila Loop ' -- Cierra el recordset y la conexión abierta .FormatString = "FECHA|HOROMETRO|DIESEL|ACEITE DE MOTOR|FILTRO DE ACEITE|FILTRO DE PETROLEO|SEPARADOR DE AGUA|ACEITE TRANSMISION|ACEITE HIDRAULICO|OBSERVACIONES" .ColWidth(0) = 1000 .ColWidth(1) = 1000 .ColWidth(2) = 1200 .ColWidth(3) = 1200 .ColWidth(4) = 1200 .ColWidth(5) = 1200 .ColWidth(6) = 1200 .ColWidth(7) = 1200 .ColWidth(8) = 1500 .ColWidth(9) = 1500 Rst.Close Cnx.Close Set Rst = Nothing Set Cnx = Nothing ' -- Establece los ancho de columna de la grilla ' -- Volver a Habilitar el repintado del Grid .Redraw = True
End WithOn Error GoTo mensaje
Sheets("Datos").Activate Range("A1").Select Cells.Find(What:=UCase(cbcodigo), After:=ActiveCell, LookIn:=xlValues, LookAt:= _ xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _ False).Activate TXTSERIE = ActiveCell.Offset(0, 2).Value TXTDSC = ActiveCell.Offset(0, 1).Value
Exit Submensaje:
MsgBox "No se encontraron registros", vbInformation, "MENSAJE" Application.ScreenUpdating = True
End Sub
Lo que busco es que al seleccionar en el combo box asigne al hoja respectibva para las consultas. No se si sera posible subir el archivo??
espero me puedan ayudar
Saludos
Oguerrero81