Visual Basic para Aplicaciones - Leer Archivos CSV

Life is soft - evento anual de software empresarial
 
Vista:
sin imagen de perfil

Leer Archivos CSV

Publicado por Victor (6 intervenciones) el 07/12/2022 14:46:17
Tengo el Siguiente código en un módulo:

Option Compare Database

Public Sub LeerCSVTratamientos()
' ---------------------------- VARIABLES -------------------------

Dim strDirArchivo As String
Dim intFila As Integer
Dim intCounterFila As Integer
Dim strLinea As String
Dim intColumna As Integer


' ------------------- ALGUNAS OTRAS VARIABLES ---------------------

Dim strMarcaOficial As String
Dim strCodigoRega As String
Dim strNumeroReceta As String
Dim strFechaReceta As String
Dim strNumeroRefrendacion As String
Dim strFechaRefrendacion As String
Dim strFechaTratamiento As String


Dim strExplotacion As String
Dim strGrupo As String
Dim strNumeroCrotal As String
Dim strNumeroInterno As String
Dim strFechaNacimiento As String
Dim strTipoAnimal As String

Dim strSexo As String
Dim strRaza As String


Dim strGuiaEntrada As String
Dim strFechaEntrada As String
Dim strMadre As String
Dim strExplotacionNacimiento As String

' --------- ARRAY() PARA GUARDAR LA CADENA DE TEXO LEIDA ----------

Dim myArrayDatos() As String


' ----------------------- LLAMAMOS EL ARCHIVO -----------------------
If IsNull(Forms!frmBovinosTratamientosPinchazo!cboMarcaOficial) Or Forms!frmBovinosTratamientosPinchazo!cboMarcaOficial = "" Then
MsgBox "Rellene los campos obligatorios", , "ATENCION"
Forms!frmBovinosTratamientosPinchazo!cboMarcaOficial.SetFocus
ElseIf IsNull(Forms!frmBovinosTratamientosPinchazo!cboNumeroReceta) Or Forms!frmBovinosTratamientosPinchazo!cboNumeroReceta = "" Then
MsgBox "Rellene los campos obligatorios", , "ATENCION"
Forms!frmBovinosTratamientosPinchazo!cboNumeroReceta.SetFocus
ElseIf IsNull(Forms!frmBovinosTratamientosPinchazo!txtFechaTratamiento) Or Forms!frmBovinosTratamientosPinchazo!txtFechaTratamiento = "" Then
MsgBox "Rellene los campos obligatorios", , "ATENCION"
Forms!frmBovinosTratamientosPinchazo!txtFechaTratamiento.SetFocus
Else
strDirArchivo = GetFileName("*.csv")

'---------------------------VALIDAMOS LA LLAMADA DEL ARCHIVO------------------------

If strDirArchivo = "" Then
MsgBox "No seleccionó ningún archivo. La acción se cancela.", , "ERROR"
Else

'-------------------------------------ABRIMOS EL ARCHIVO------------------------------
Open strDirArchivo For Input As #1

'-----------------------------CREAMOS LA ITERACION PARA VALIDAR QUE LA PRIMERA LINEA DEL ARCHIVO TENGA LOS DATOS QUE QUEREMOS
Do
Line Input #1, strLinea

'---------------------------------DIVIDIMOS LA CADENA DE TEXTO LEÍDA---------------------------
myArrayDatos() = Split(strLinea, ";")

'------------------------------ASIGNAMOS LOS VALORES DE LA MATRIZ A LAS VARIABLES-----------------------------
strExplotacion = myArrayDatos(0)
strGrupo = myArrayDatos(1)
strNumeroCrotal = myArrayDatos(2)
strNumeroInterno = myArrayDatos(3)
strFechaNacimiento = myArrayDatos(4)
strTipoAnimal = myArrayDatos(5)
strGuiaEntrada = myArrayDatos(6)
strFechaEntrada = myArrayDatos(7)
strMadre = myArrayDatos(8)
strExplotacionNacimiento = myArrayDatos(9)

'------------------------------------VALIDAMOS LOS CAMPOS DEL ARCHIVO--------------------------------
If strExplotacion = "EXPLOTACION" _
And strGrupo = "GRUPO" _
And strNumeroCrotal = "CROTAL" _
And strNumeroInterno = "INTERNO" _
And strFechaNacimiento = "FECHA_N" _
And strTipoAnimal = "TIPO_ANIMAL" _
And strGuiaEntrada = "GUIA_E" _
And strFechaEntrada = "FECHA_E" _
And strMadre = "MADRE" _
And strExplotacionNacimiento = "EXPLOT_NAC" Then


'-----------------------------CREAMOS LA ITERACION PARA LEER LA INFORMACIÓN DEL ARCHIVO-------------------
Do While Not EOF(1)

Line Input #1, strLinea

----------------------------------DIVIDIMOS LA CADENA DE TEXTO DEVUELTA---------------------
myArrayDatos() = Split(strLinea, ";")

'EXTRAEMOS LOS VALORES DE LOS CAMPOS DEL FORMULARIO
strMarcaOficial = Forms!frmBovinosTratamientosPinchazo!cboMarcaOficial
strCodigoRega = Forms!frmBovinosTratamientosPinchazo!txtCodigoREGA
strNumeroReceta = Forms!frmBovinosTratamientosPinchazo!cboNumeroReceta
strFechaReceta = Forms!frmBovinosTratamientosPinchazo!txtFechaReceta
strFechaTratamiento = Forms!frmBovinosTratamientosPinchazo!txtFechaTratamiento

'VALIDAMOS EL CAMPO (***NUMERO_REFRENDACION***)
If IsNull(Forms!frmBovinosTratamientosPinchazo!cboNumeroRefrendacion) Then
strNumeroRefrendacion = ""
Else
strNumeroRefrendacion = Forms!frmBovinosTratamientosPinchazo!cboNumeroRefrendacion
End If

'VALIDAMOS EL CAMPO (***FECHA_TRATAMIENTO***)
If IsNull(Forms!frmBovinosTratamientosPinchazo!txtFechaRefrendacion) Then
strNumeroRefrendacion = ""
Else
strFechaRefrendacion = Forms!frmBovinosTratamientosPinchazo!txtFechaRefrendacion
End If



'ASIGNAMOS LOS VALORES DIVIDIDOS A LAS VARIABLES
strExplotacion = myArrayDatos(0)
strGrupo = myArrayDatos(1)
strNumeroCrotal = myArrayDatos(2)
strFechaNacimiento = myArrayDatos(4)
strTipoAnimal = myArrayDatos(5)
strGuiaEntrada = myArrayDatos(6)
strFechaEntrada = myArrayDatos(7)
strMadre = myArrayDatos(8)
strExplotacionNacimiento = myArrayDatos(9)

'EXTRAEMOS LOS ULTIMOS CUATRO NUMEROS DEL CROTAL
strNumeroInterno = Right(strNumeroCrotal, 4)

'DIVIDIMOS EL TIPO DE ANIMAL PARA EXTRAER EL SEXO Y LA RAZA
strSexo = Left(strTipoAnimal, 1)
strRaza = Right(strTipoAnimal, 4)

'CREAMOS UNA VARIABLE SQL, PARA INSERTAR LOS DATOS EN LA TABLA
Dim strSQL As String

If strExplotacion = strMarcaOficial Then
'CREAMOS LA CONSULTA DE INSERCION
strSQL = "INSERT INTO tblBovinosTratamientosPinchazo VALUES ('" & strMarcaOficial & "', '" & strCodigoRega & "', '" & strNumeroReceta & "', " _
& "'" & strFechaReceta & "', '" & strNumeroRefrendacion & "', '" & strFechaRefrendacion & "', '" & strFechaTratamiento & "', '" & strGrupo & "', " _
& "'" & strNumeroCrotal & "', '" & strNumeroInterno & "', '" & strFechaNacimiento & "', '" & strSexo & "', '" & strRaza & "', '" & strGuiaEntrada & "', " _
& "'" & strFechaEntrada & "', '" & strMadre & "', '" & strExplotacionNacimiento & "');"

'QUITAMOS LOS AVISOS
DoCmd.SetWarnings False
'EJECUTAMOS LA CONSULTA
DoCmd.RunSQL strSQL
Else
MsgBox "Los datos que intenta importar, no pertenecen a la explotación escogida, vbOKOnly"
End If
Loop
' MENSAJE DE CONFIRMACIÓN AL USUARIO
MsgBox "Datos importados correctamente.", vbOKOnly
Else
' MENSAJE DE INFORMACIÓN AL USUARIO
MsgBox "El archivo no tiene el formato correcto de lectura. Verifique los campos!", vbOKOnly + vbInformation, "Informacion"
End If
Loop While BOF = -1

End If
'CERRAMOS EL ARCHIVO ABIERTO
Close 1

'RECETEAMOS LOS CAMPOS DEL FORMULARIO
Forms!frmBovinosTratamientosPinchazo!cboMarcaOficial = ""
Forms!frmBovinosTratamientosPinchazo!txtCodigoREGA = ""
Forms!frmBovinosTratamientosPinchazo!cboNumeroReceta = ""
Forms!frmBovinosTratamientosPinchazo!txtFechaReceta = ""
Forms!frmBovinosTratamientosPinchazo!cboNumeroRefrendacion = ""
Forms!frmBovinosTratamientosPinchazo!txtFechaRefrendacion = ""
Forms!frmBovinosTratamientosPinchazo!txtFechaTratamiento = ""

'REFRESCAMOS EL FORMULARIO
Forms!frmBovinosTratamientosPinchazo!.Refresh
End If
End Sub

Function GetFileName(Optional InitialName As String) As String
With Application.FileDialog(1)
.InitialFileName = InitialName
If .Show Then
GetFileName = .SelectedItems(1)
End If
End With
End Function

---------------------------------------------------------------------------------------------------------------------------------------------------

Mi problema es que el modulo funcionaba en la versión de access 2019 basado en 32 bits y ahora lo intento utilizar en access 365 basado en 32 bits y no me funciona. Me podéis ayudar a ver cual puede ser el problema, porque veo que al menos la primera linea me la lee validando los campos y me inserta la primera linea de datos. Y ahí para.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil

Leer Archivos CSV

Publicado por Victor (6 intervenciones) el 28/12/2022 11:17:17
Buenas,

Hoy me había puesto a resolver el problema, y lo peor, el problema estaba en la tabla, tenia un campo que no permitía duplicado, pero en realidad es necesario que ese campo permita duplicados.

Gracias, si al menos leíste para intentar ayudar!

Un saludo
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar