VERSION 5.00
Object = "{0F987290-56EE-11D0-9C43-00A0C90F29FC}#1.0#0"; "ActBar.ocx"
Object = "{B02F3647-766B-11CE-AF28-C3A2FBE76A13}#2.5#0"; "ss32x25.ocx"
Object = "{CDF3B183-D408-11CE-AE2C-0080C786E37D}#2.1#0"; "Edt32x20.ocx"
Object = "{00025600-0000-0000-C000-000000000046}#5.2#0"; "crystl32.ocx"
Begin VB.Form FCO5010 
   Caption         =   "Proceso reportes"
   ClientHeight    =   5790
   ClientLeft      =   60
   ClientTop       =   345
   ClientWidth     =   8100
   BeginProperty Font 
      Name            =   "Arial"
      Size            =   8.25
      Charset         =   0
      Weight          =   400
      Underline       =   0   'False
      Italic          =   0   'False
      Strikethrough   =   0   'False
   EndProperty
   Icon            =   "ProcesoReportes.frx":0000
   KeyPreview      =   -1  'True
   LinkTopic       =   "Form1"
   MaxButton       =   0   'False
   MDIChild        =   -1  'True
   ScaleHeight     =   5790
   ScaleWidth      =   8100
   Begin FPSpread.vaSpread sprDatos 
      Bindings        =   "ProcesoReportes.frx":030A
      Height          =   3825
      Left            =   240
      OleObjectBlob   =   "ProcesoReportes.frx":0320
      TabIndex        =   9
      Top             =   840
      Width           =   7560
   End
   Begin EditLib.fpLongInteger txtMes 
      Height          =   285
      Left            =   5325
      TabIndex        =   6
      Top             =   495
      Width           =   615
      _Version        =   131072
      _ExtentX        =   1085
      _ExtentY        =   503
      _StockProps     =   68
      BackColor       =   -2147483643
      ForeColor       =   -2147483640
      ThreeDInsideStyle=   1
      ThreeDInsideHighlightColor=   -2147483633
      ThreeDInsideShadowColor=   -2147483642
      ThreeDInsideWidth=   1
      ThreeDOutsideStyle=   1
      ThreeDOutsideHighlightColor=   16777215
      ThreeDOutsideShadowColor=   -2147483632
      ThreeDOutsideWidth=   1
      ThreeDFrameWidth=   0
      BorderStyle     =   0
      BorderColor     =   -2147483642
      BorderWidth     =   1
      ButtonDisable   =   0   'False
      ButtonHide      =   0   'False
      ButtonIncrement =   1
      ButtonMin       =   1
      ButtonMax       =   100
      ButtonStyle     =   1
      ButtonWidth     =   0
      ButtonWrap      =   -1  'True
      ButtonDefaultAction=   -1  'True
      ThreeDText      =   0
      ThreeDTextHighlightColor=   -2147483633
      ThreeDTextShadowColor=   -2147483632
      ThreeDTextOffset=   1
      AlignTextH      =   2
      AlignTextV      =   1
      AllowNull       =   0   'False
      NoSpecialKeys   =   3
      AutoAdvance     =   0   'False
      AutoBeep        =   0   'False
      CaretInsert     =   0
      CaretOverWrite  =   3
      UserEntry       =   0
      HideSelection   =   -1  'True
      InvalidColor    =   -2147483637
      InvalidOption   =   0
      MarginLeft      =   3
      MarginTop       =   3
      MarginRight     =   3
      MarginBottom    =   3
      NullColor       =   -2147483637
      OnFocusAlignH   =   0
      OnFocusAlignV   =   0
      OnFocusNoSelect =   0   'False
      OnFocusPosition =   0
      ControlType     =   0
      Text            =   "0"
      MaxValue        =   "12"
      MinValue        =   "1"
      NegFormat       =   1
      NegToggle       =   0   'False
      Separator       =   ""
      UseSeparator    =   0   'False
      IncInt          =   1
      BorderGrayAreaColor=   -2147483637
      ThreeDOnFocusInvert=   0   'False
      ThreeDFrameColor=   -2147483633
      Appearance      =   0
      BorderDropShadow=   0
      BorderDropShadowColor=   -2147483632
      BorderDropShadowWidth=   3
      MouseIcon       =   "ProcesoReportes.frx":04F9
   End
   Begin EditLib.fpLongInteger txtAnio 
      Height          =   285
      Left            =   4605
      TabIndex        =   5
      Top             =   495
      Width           =   705
      _Version        =   131072
      _ExtentX        =   1244
      _ExtentY        =   503
      _StockProps     =   68
      BackColor       =   -2147483643
      ForeColor       =   -2147483640
      ThreeDInsideStyle=   1
      ThreeDInsideHighlightColor=   -2147483633
      ThreeDInsideShadowColor=   -2147483642
      ThreeDInsideWidth=   1
      ThreeDOutsideStyle=   1
      ThreeDOutsideHighlightColor=   16777215
      ThreeDOutsideShadowColor=   -2147483632
      ThreeDOutsideWidth=   1
      ThreeDFrameWidth=   0
      BorderStyle     =   0
      BorderColor     =   -2147483642
      BorderWidth     =   1
      ButtonDisable   =   0   'False
      ButtonHide      =   0   'False
      ButtonIncrement =   1
      ButtonMin       =   1
      ButtonMax       =   100
      ButtonStyle     =   1
      ButtonWidth     =   0
      ButtonWrap      =   -1  'True
      ButtonDefaultAction=   -1  'True
      ThreeDText      =   0
      ThreeDTextHighlightColor=   -2147483633
      ThreeDTextShadowColor=   -2147483632
      ThreeDTextOffset=   1
      AlignTextH      =   2
      AlignTextV      =   1
      AllowNull       =   0   'False
      NoSpecialKeys   =   3
      AutoAdvance     =   0   'False
      AutoBeep        =   0   'False
      CaretInsert     =   0
      CaretOverWrite  =   3
      UserEntry       =   0
      HideSelection   =   -1  'True
      InvalidColor    =   -2147483637
      InvalidOption   =   0
      MarginLeft      =   3
      MarginTop       =   3
      MarginRight     =   3
      MarginBottom    =   3
      NullColor       =   -2147483637
      OnFocusAlignH   =   0
      OnFocusAlignV   =   0
      OnFocusNoSelect =   0   'False
      OnFocusPosition =   0
      ControlType     =   0
      Text            =   "0"
      MaxValue        =   "2078"
      MinValue        =   "2002"
      NegFormat       =   1
      NegToggle       =   0   'False
      Separator       =   ""
      UseSeparator    =   0   'False
      IncInt          =   1
      BorderGrayAreaColor=   -2147483637
      ThreeDOnFocusInvert=   0   'False
      ThreeDFrameColor=   -2147483633
      Appearance      =   0
      BorderDropShadow=   0
      BorderDropShadowColor=   -2147483632
      BorderDropShadowWidth=   3
      MouseIcon       =   "ProcesoReportes.frx":0515
   End
   Begin VB.TextBox txtNomRep 
      Height          =   285
      Left            =   1350
      TabIndex        =   4
      Top             =   495
      Width           =   3240
   End
   Begin VB.TextBox txtAdm 
      Height          =   285
      Left            =   5955
      TabIndex        =   7
      Top             =   495
      Width           =   795
   End
   Begin VB.TextBox txtReporte 
      Height          =   285
      Left            =   480
      TabIndex        =   3
      Top             =   495
      Width           =   870
   End
   Begin VB.TextBox txtSucursal 
      Height          =   285
      Left            =   6750
      TabIndex        =   8
      Top             =   495
      Width           =   795
   End
   Begin VB.CheckBox chkRegenerar 
      Caption         =   "Regenerar Información"
      Height          =   195
      Left            =   5445
      TabIndex        =   2
      Top             =   120
      Width           =   2055
   End
   Begin Crystal.CrystalReport crptReport 
      Left            =   6960
      Top             =   4770
      _ExtentX        =   741
      _ExtentY        =   741
      _Version        =   348160
      PrintFileLinesPerPage=   60
   End
   Begin VB.Label lblFiltro 
      BackStyle       =   0  'Transparent
      Caption         =   "Filtro ..."
      BeginProperty Font 
         Name            =   "Arial"
         Size            =   8.25
         Charset         =   0
         Weight          =   700
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      ForeColor       =   &H00C00000&
      Height          =   375
      Left            =   240
      TabIndex        =   10
      Top             =   4695
      Width           =   6120
      WordWrap        =   -1  'True
   End
   Begin VB.Label lblAdm 
      BackStyle       =   0  'Transparent
      ForeColor       =   &H00800000&
      Height          =   210
      Left            =   1440
      TabIndex        =   1
      Top             =   120
      Width           =   3285
   End
   Begin VB.Label lblLabels 
      AutoSize        =   -1  'True
      BackStyle       =   0  'Transparent
      Caption         =   "Administradora:"
      Height          =   210
      Index           =   0
      Left            =   240
      TabIndex        =   0
      Top             =   105
      Width           =   1140
   End
   Begin ActiveBarLibraryCtl.ActiveBar abToolbar 
      Left            =   7425
      Top             =   4740
      _ExtentX        =   847
      _ExtentY        =   847
      BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
         Name            =   "Arial"
         Size            =   8.25
         Charset         =   0
         Weight          =   400
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      Bands           =   "ProcesoReportes.frx":0531
   End
End
Attribute VB_Name = "FCO5010"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private WithEvents clsSpread As NSpread
Attribute clsSpread.VB_VarHelpID = -1
Private MAdo As ODBC.ODBCDirecto
Private MiCx As Integer 'Conexión
Private MiX As Integer 'Ancho de la forma
Private MiY As Integer 'Alta de la forma

'Para Bitacora
Private MBitacora As New ADAMBitacora.Bitacora
Private MbRenovar As Boolean

'Para Consulta a la BD
Private MsOrden As String
Private MsSql As String

'Parametros
Private MsAño As String
Private MsMes As String
Private MsDato As String
Private MsSUC As String

'Entidad Administradora
Private MsNomEnt As String
Private MsNitEnt As String
Private MsDiVe As String

'Encabezado Reportes
Private MsTabla As String   'Parte comun del nombre de las tablas de autoliquidacion
Private MsC01A As String    'Razón social
Private MsC02A As String    'NIT/CC/CE
Private MsC02B As String    'Numero Id
Private MsC03A As String    'Clase de Aportante P/G
Private MsC04A As String    'Direccion
Private MsC04B As String    'Nombre Ciudad
Private MsC04C As String    'Codigo Ciudad
Private MsC04D As String    'Nombre Departamento
Private MsC04E As String    'Codigo Departamento
Private MsC04F As String    'Telefono
Private MsC04G As String    'Fax
Private MsC05A As String    'Periodo de cotizacion
Private MsC08A As String    'Forma de presentacion U/C/S
Private MsC08B As String    'Codigo sucursal
Private MsC09A As String    'Nro total de trabajadores
Private MsC09B As String    'Nro de afiliados al ISS en Pension
Private MsC09C As String    'Nro de afiliados al ISS en Salud
Private MsC10A As String    'Nro de afiliados
Private MsSucP As String
Private MsNumReg As String
Private MsNroPat As String

Private MnSGSS As SGSS      'Sistema General de Seguridad Social
Private MbMedioMagnetico As Boolean 'Es medio magnético
Private MsRuta As String
Private MsCalif As String
Private MbPrimeraVezAc As Boolean
Private MbPrimeraVezPr As Boolean
Private MiXAnt          As Integer    'Variables a utilizar en la rutina de Resize
Private MiYAnt          As Integer
Private MbHuboError As Boolean
Private MsEsNulo As String

Private MsWhereAdi As String
Private MiKey As Integer
Private MbOrdenAsc As Boolean
Private MsAntOrden As String

Private MsOrdenRep As String

Private Sub abToolbar_Click(ByVal Tool As ActiveBarLibraryCtl.Tool)
    Select Case LCase(Tool.Name)
        Case "tlseltodo": SeleccionaRegistros sprDatos, "1"
        Case "tlselnada": SeleccionaRegistros sprDatos, "0"
        Case "tlalta": Altas
        Case "tlbaja": Bajas
        Case "tlguarda": GuardaCambios
        Case "tlordena": OrdenarDatos
        Case "tlrenueva": RenovarDatos
        Case "tlpreview": GenerarReporte sprDatos.ActiveRow, crptToWindow, True
        Case "tlejecuta": Procesar
        Case "tltrabaja": TrabajarCon
        Case "tlfiltro": Filtro
        Case "tlsalida": Unload Me
    End Select
End Sub

Private Sub chkRegenerar_Click()
    Dim AuxAño As Variant
    Dim AuxMes As Variant
    
    If chkRegenerar.Value = vbChecked Then
        sprDatos.GetText 4, sprDatos.ActiveRow, AuxAño
        sprDatos.GetText 5, sprDatos.ActiveRow, AuxMes
        If (AuxAño - 2000) * 12 + AuxMes < (Year(Date) - 2000) * 12 + Month(Date) - 1 Then
            If clsMsgbox.Mensaje("¿Esta seguro de querer regenerar información para periodos anteriores?", mSiNoCancelar, mConfirma, GsTitMsg) <> vbYes Then
                chkRegenerar.Value = vbUnchecked
            End If
        End If
    End If
End Sub

Private Sub Form_Activate()
    If MbPrimeraVezAc Then
        MbPrimeraVezAc = False
        If Not MDIChild Then
            WindowState = 0
            Move (Screen.Width - Width) \ 2, (Screen.Height - Height) \ 2
            Screen.MousePointer = vbDefault
        End If
    End If
End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    Select Case KeyCode
        Case vbKeyF3: Unload Me
        Case vbKeyF5: RenuevaDatos
        Case vbKeyF6: Altas: KeyCode = 0
        Case vbKeyF7
            Screen.MousePointer = vbHourglass
            MBitacora.mBorra
            Screen.MousePointer = vbDefault
        Case vbKeyF12: abToolbar.Bands(1).TrackPopup -1, -1
    End Select
End Sub

Private Sub Form_Load()
    Dim Aux As Variant
    GbAError = False
    Me.Tag = GiVenMax%
    Gven(Val(Me.Tag)).icx = Gicx%
    MiCx = Gven(Val(Me.Tag)).icx
    Set MAdo = Gtc(MiCx).Ado
    Me.Icon = LoadPicture(sIconoForma)
    
'    Checa nivel de seguridad
    Gven(Val(Me.Tag)).iNivSeguridad = iObtenNivSeguridad(GsOper, GsUid, MiCx)
    If Gven(Val(Me.Tag)).iNivSeguridad = 0 Then
        Screen.MousePointer = vbDefault
        Me.Top = -10000
        GbAError = True
        Exit Sub
    End If
    
    Set clsSpread = New NSpread
    GAdam.ObtieneColores
    
    If Not MDIChild Then
        WindowState = 0
        Move (Screen.Width - Width) \ 2, (Screen.Height - Height) \ 2
        Screen.MousePointer = vbDefault
    End If
    
    'Tamaño de la forma
    If Me.WindowState = 0 Then
        MiX = 8220
        MiY = 6195
        Me.Width = MiX
        Me.Height = MiY
    End If
        
    MbPrimeraVezAc = True
    MbPrimeraVezPr = True
    
    If Left(UCase(GsDsn), 3) = "ORA" Then
        MsEsNulo = "Nvl"
    Else
        MsEsNulo = "IsNull"
    End If
    Caption = GsDsn & " / " & GsCveCia & " - Proceso Reportes"
    AsignaIconos abToolbar, 3, LALTA, LBAJA, LSELTODO, LSELNADA, LFILTRO, LORDENA, LRENUEVA, LPREVIEW, LEJECUTA, LTRABAJA, LGUARDA, LSALIDA
    ToolInicioGrupo abToolbar, 3, True, 2, 4, 6, 8

    MsCalif = ""
    'If Mid(UCase(GSDsn), 1, 3) = "ORA" Then MSCalif = "ADAM."
    MsOrden = " ORDER BY Secuencia"
    MsWhereAdi = " AND 1=2"
    
    sprDatos.GetText 10, 1, Aux
    lblAdm = CStr(Aux)
    MiYAnt = Me.Height
    MiXAnt = Me.Width
    
    txtAnio = IIf(Month(Date) = 12, Year(Date) - 1, Year(Date))
    txtMes = IIf(Month(Date) = 1, 12, Month(Date) - 1)
    
    CreaBitacora
    MiKey = vbKeyReturn
    AplicaFiltros
    
End Sub

Private Sub Form_MouseUp(Button As Integer, Shift As Integer, x As Single, y As Single)
    If Button = 2 Then abToolbar.Bands(1).TrackPopup -1, -1
End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
    If iDeseaGuardarCambios = 2 Then Cancel = True
    Set MAdo = Nothing
    Set MBitacora = Nothing
    Set clsSpread = Nothing
    Gtc(MiCx).ihijas = Gtc(MiCx).ihijas - 1
    Set FCO5010 = Nothing
    
End Sub

'Private Sub Form_Resize()
'   If Not MbPrimeraVezAc Then
'      If Me.WindowState <> 1 Then
'          GAdam.MaximizaControles Me, 1, 1, 7600, 5300, MiX, MiY, True, True, True, -1
'          MiYAnt = Me.Height
'          MiXAnt = Me.Width
'      End If
'   End If
'End Sub

Private Sub Form_Unload(Cancel As Integer)
    If GbExterno Then End
End Sub

Private Sub sprDatos_Click(ByVal Col As Long, ByVal Row As Long)
    If Col = 1 Then MBitacora.mCambia
End Sub

Private Sub sprDatos_DblClick(ByVal Col As Long, ByVal Row As Long)
    GenerarReporte sprDatos.ActiveRow, crptToWindow, True
End Sub

Private Sub sprDatos_KeyDown(KeyCode As Integer, Shift As Integer)
    If MbPrimeraVezPr Then Form_KeyDown KeyCode, Shift: MbPrimeraVezPr = False
End Sub

Private Sub sprDatos_LeaveCell(ByVal Col As Long, ByVal Row As Long, ByVal NewCol As Long, ByVal NewRow As Long, Cancel As Boolean)
    Dim Aux As Variant
    If NewRow = -1 Then Exit Sub
    sprDatos.GetText 9, NewRow, Aux
    lblAdm = CStr(Aux)
    chkRegenerar.Value = vbUnchecked
End Sub

Private Sub Altas()
    On Error Resume Next
    GuardaCambios
    FCO5010A.Show 1
    txtReporte = ""
    txtNomRep = ""
    txtAdm = ""
    txtSucursal = ""
    txtAnio.Text = GsAño
    txtMes.Text = GsMes
    AplicaFiltros
    'sprDatos.Row = sprDatos.MaxRows
    'sprDatos.Col = 1
    'sprDatos.Action = 0
End Sub

Private Sub Bajas()
    If sprDatos.VirtualMaxRows <= 0 Then Exit Sub
    MBitacora.mBorra
End Sub

Private Sub Filtro()
    frmFiltroAgr.Show 1
    lblFiltro = GsFiltroTit
End Sub

Private Sub ConfiguraSpread()
    sprDatos.VisibleCols = 7
    With sprDatos
        .Visible = False
        .Action = 28
        GAdam.ConfiguracionSpread sprDatos
        
        .Row = 0:
        .Col = 1: .Text = " "
        .Col = 2: .Text = "Cod."
        .Col = 3: .Text = "Nombre Reporte"
        .Col = 4: .Text = "Año"
        .Col = 5: .Text = "Mes"
        .Col = 6: .Text = "Adm"
        .Col = 7: .Text = "Sucursal"
        .Col = 8: .Text = "Secuencia": .ColHidden = True
        .Col = 9: .Text = "Descripcion": .ColHidden = True
        ConfiguraSpreadJCL sprDatos
        .Visible = False
    End With
End Sub

Private Sub CreaBitacora()
   MBitacora.mCreaBitacora sprDatos, MAdo.lhEnv, MAdo.lhDbc, MAdo.lhstmt, MAdo
   MBitacora.p_ConfirmaBaja = True
   MBitacora.mDefineLlave 2
   MBitacora.mTablaSPInfo 1, "sp_fco_baja_proc_reportes_ala", "'" & GsCveCia & "'", 2, 4, 5, 6, 7
   MBitacora.mTablaSPInfo 2, "sp_fco_upd_proc_reportes_ala", 1, "'" & GsCveCia & "'", 2, 4, 5, 6, 7
   MBitacora.mColNoNulls 2
End Sub

Private Sub GenerarDatosDetalle()
    On Error GoTo AclararError
    Dim sMM As String
    Dim sReg As String
        
    If Mid$(UCase(GsDsn), 1, 3) = "ORA" Then
        sMM = IIf(MbMedioMagnetico, "True", "False")
        sReg = IIf(chkRegenerar.Value = vbChecked, "True", "False")
    Else
        sMM = IIf(MbMedioMagnetico, "1", "0")
        sReg = IIf(chkRegenerar.Value = vbChecked, 1, 0)
    End If

    Select Case MnSGSS
        Case Salud
            MAdo.Sql = "sp_fco_crea_salud '" & GsCveCia & "'" & "," & MsAño & "," & MsMes & ",'" & MsSUC & "','" & MsDato & "'," & sMM & "," & sReg
        Case Pensiones
            MAdo.Sql = "sp_fco_crea_pension '" & GsCveCia & "'" & "," & MsAño & "," & MsMes & ",'" & MsSUC & "','" & MsDato & "'," & sMM & "," & sReg
        Case Riesgos
            MAdo.Sql = "sp_fco_crea_riesgos '" & GsCveCia & "'" & "," & MsAño & "," & MsMes & ",'" & MsSUC & "'," & sMM & "," & sReg
        Case ISS_Consolidado
            MAdo.Sql = "sp_fco_crea_vw_iss '" & GsCveCia & "'" & "," & MsAño & "," & MsMes & ",'" & MsSUC & "'," & sMM & "," & sReg
        Case ISS_Integrado
            MAdo.Sql = "sp_fco_crea_ISS '" & GsCveCia & "'" & "," & MsAño & "," & MsMes & ",'" & MsSUC & "'," & sMM & "," & sReg
    End Select
    If MAdo.ExecSQL = -1 Then GoTo AclararError
    
    Exit Sub
AclararError:
    MbHuboError = True
    Screen.MousePointer = vbDefault
    If Err > 0 Then
        clsMsgbox.Mensaje Err.Description, mAceptar, mAdvierte, GsTitMsg
    End If

End Sub

Private Sub GenerarReporte(Fila As Integer, Destino As Crystal.DestinationConstants, Preliminar As Boolean)
    If Fila < 0 Then Exit Sub
    On Error GoTo RutaNoExiste
        
    Screen.MousePointer = vbHourglass
    
    Dim i As Integer
    Dim sPath As String
    Dim sCarpeta As String
    Dim sSep As String
    Dim sFuncSub As String
    Dim nRetVal As Long
    Dim sSeg As String
    Dim sTabla As String
    
    MbHuboError = False

    'Hallar de que sistema de seguridad social es el reporte
    'y recuperar nombre de la tabla
    MnSGSS = Ninguno
    HallarSistema Fila
    If MnSGSS = Ninguno Then Exit Sub

    GenerarDatosDetalle
    If MbHuboError Then Exit Sub
    
    If Not MbMedioMagnetico Then  ' REPORTE IMPRESO
        HallarDatosCabecera
        HallarDatosPie
        HallarOrden
        With crptReport
            .WindowShowPrintSetupBtn = True
            .WindowShowSearchBtn = True
            
            .Connect = "DSN = " & UCase(GsDsn) & _
                "; UID = " & GsUid & _
                "; PWD = " & GsPwd
            .ReportFileName = MsRuta
            If Trim(MsRuta) = "" Then
                Screen.MousePointer = vbDefault
                clsMsgbox.Mensaje "No se ha definido la ruta del reporte modelo (*.rpt)." & _
                vbCrLf & "Debe configurarla por Definición de Reportes de Autoliquidación", mAceptar, mAdvierte, GsTitMsg
                Exit Sub
            End If
            .ReplaceSelectionFormula ""

            'Limpiar Formulas
            For i = 0 To 19
                .Formulas(i) = ""
            Next i
            
            .Destination = Destino
            
            Select Case MnSGSS
                Case Salud
                    sTabla = "MF_EPS"
                Case Pensiones
                    sTabla = "MF_FPO"
                Case Riesgos
                    sTabla = "MF_ARP"
                Case ISS_Consolidado
                    sTabla = "VW_ISS"
                Case ISS_Integrado
                    sTabla = "MF_ISS"
            End Select
            
            sSeg = _
            " (COD_TRAB IN " & _
             " (SELECT tg.trabajador FROM trabajadores_grales tg " & _
              " WHERE tg.compania = " & sTabla & ".cia " & _
                " AND tg.trabajador = " & sTabla & ".cod_trab " & _
                " AND compania = '" & GsCveCia & "' " & _
                " AND clase_nomina IN (SELECT clase_nomina FROM rel_usu_clase_nom  " & _
                                     " WHERE upper(usuario) = '" & UCase(GsUsuario) & "')) OR " & _
             " (COD_TRAB IN (SELECT ff.trabajador FROM fco_fantasmas ff WHERE ff.compania = " & sTabla & ".cia)))" & _
             " AND COD_TRAB NOT IN " & _
             " (SELECT b.trabajador FROM rel_usu_agr_trab a, rel_trab_agr b " & _
             " WHERE a.agrupacion = b.agrupacion and a.dato = b.dato " & _
             " and a.usuario = '" & GsUid & "' " & _
             " and b.compania = " & sTabla & ".cia " & _
             " and b.trabajador = " & sTabla & ".cod_trab " & _
             " and b.compania = '" & GsCveCia & "')"
                                                                           
            Select Case MnSGSS
                Case Salud
                    .SQLQuery = "Select * From " & MsTabla & " MF_EPS" & _
                    " Where COD_EPS='" & MsDato & "'" & _
                    IIf(MsSUC = "", " AND ", " And COD_SUC='" & MsSUC & "' AND ") & sSeg & GsFiltroAgr
                Case Pensiones
                    .SQLQuery = "Select * From " & MsTabla & " MF_FPO" & _
                    " Where COD_FPO='" & MsDato & "'" & _
                    IIf(MsSUC = "", " AND ", " And COD_SUC='" & MsSUC & "' AND ") & sSeg & GsFiltroAgr
                Case Riesgos
                    .SQLQuery = "Select * From " & MsTabla & " MF_ARP" & _
                    IIf(MsSUC = "", " WHERE ", " WHERE COD_SUC='" & MsSUC & "' AND ") & sSeg & GsFiltroAgr
                Case ISS_Consolidado
                    .SQLQuery = "Select * From " & MsTabla & " VW_ISS" & _
                    IIf(MsSUC = "", " WHERE ", " Where COD_SUC='" & MsSUC & "' AND ") & sSeg & GsFiltroAgr
                Case ISS_Integrado
                    .SQLQuery = "Select * From " & MsTabla & " MF_ISS" & _
                    IIf(MsSUC = "", " WHERE ", " Where COD_SUC='" & MsSUC & "' AND ") & sSeg & GsFiltroAgr
            End Select
                                        
            If MnSGSS <> ISS_Consolidado Then
                .Formulas(0) = "Entidad='" & MsNomEnt & "'"
                .Formulas(1) = "NIT_Entidad='" & MsNitEnt & "-" & MsDiVe & "'"
                .Formulas(2) = "C01A='" & MsC01A & "'"
                .Formulas(3) = "C02A='" & MsC02A & "'"
                .Formulas(4) = "C02B='" & MsC02B & "'"
                .Formulas(5) = "C03A='" & MsC03A & "'"
                .Formulas(6) = "C04A='" & MsC04A & "'"
                .Formulas(7) = "C04B='" & MsC04B & "'"
                .Formulas(8) = "C04C='" & MsC04C & "'"
                .Formulas(9) = "C04D='" & MsC04D & "'"
                .Formulas(10) = "C04E='" & MsC04E & "'"
                .Formulas(11) = "C04F='" & MsC04F & "'"
                .Formulas(12) = "C04G='" & MsC04G & "'"
                .Formulas(13) = "C05A='" & MsC05A & "'"
                .Formulas(14) = "C08A='" & MsC08A & "'"
                .Formulas(15) = "C08B='" & MsC08B & "'"
                .Formulas(16) = "C09A='" & MsC09A & "'"
                .Formulas(17) = "C10A='" & MsC10A & "'"
            Else
                .Formulas(0) = "C01A='" & MsC01A & "'"
                .Formulas(1) = "C02A='" & MsC02A & "'"
                .Formulas(2) = "C02B='" & MsC02B & "'"
                .Formulas(3) = "C04A='" & MsC04A & "'"
                .Formulas(4) = "C04B='" & MsC04B & "'"
                .Formulas(5) = "C04C='" & MsC04C & "'"
                .Formulas(6) = "C04D='" & MsC04D & "'"
                .Formulas(7) = "C04E='" & MsC04E & "'"
                .Formulas(8) = "C04F='" & MsC04F & "'"
                .Formulas(9) = "C05A='" & MsC05A & "'"
                .Formulas(10) = "C08B='" & MsC08B & "'"
                .Formulas(11) = "C09A='" & MsC09A & "'"
                .Formulas(12) = "C09B='" & MsC09B & "'"
                .Formulas(13) = "C09C='" & MsC09C & "'"
                .Formulas(14) = "C09D='" & MsNumReg & "'"
                .Formulas(15) = "CNP='" & MsNroPat & "'"
            End If
            If MnSGSS = ISS_Integrado Then
                .Formulas(17) = "C10A='" & MsC09B & "'"
                .Formulas(18) = "C10B='" & MsC09C & "'"
                .Formulas(19) = "C09D='" & MsNumReg & "'"
            End If
            .MarginLeft = 0
            .WindowState = crptNormal
            
            'Temporal para depurar Triple-A
            'Clipboard.Clear
            'Dim sFormulas As String
            'For i = 0 To 19
            '     sFormulas = sFormulas & " - F." & CStr(i) & ":" & .Formulas(i)
            'Next i
            'Clipboard.SetText sFormulas
            
            .Action = 1
        End With
    Else ' MEDIOS MAGNETICOS
        
        sSep = IIf(Trim(Right(MsRuta, 1)) = "\", "", "\")
        'Carpetas por Compañia
        sCarpeta = Trim(MsRuta) & sSep & Trim(GsCveCia)
        If Dir(sCarpeta, vbDirectory) = "" Then MkDir sCarpeta
        If MnSGSS <> ISS_Consolidado And MnSGSS <> Riesgos Then
            sCarpeta = sCarpeta & "\" & Trim(MsDato)
        End If
        
        If Dir(sCarpeta, vbDirectory) = "" Then MkDir sCarpeta
        If MsSUC <> "" Then 'Si son varias sucursales crear una carpeta por cada una
            sCarpeta = sCarpeta & "\" & MsSUC
            If Dir(sCarpeta, vbDirectory) = "" Then MkDir sCarpeta
        End If
        If MnSGSS = ISS_Consolidado Then 'Una carpeta por periodo para que no se reemplazen
            sCarpeta = sCarpeta & "\" & Trim(MsAño & sRellenar(MsMes, "0", 0, 2))
            If Dir(sCarpeta, vbDirectory) = "" Then MkDir sCarpeta
        End If
        
        If MnSGSS = ISS_Consolidado Then
            HallarDatosCabecera
            'Armar CintI
            Open sCarpeta & "\CINTI" For Output As #1
            Print #1, "000000000000000000000000" & sRellenar(sTratarNit(MsC02B), "0", 0, 11) & sHallarDV(MsC02B) & sRellenar(MsSucP, "0", 0, 3) & "000000000000000000000" & Format(Date, "yyyymmdd") & "00001000000000000000000000000" & Space(229)
            Close #1
            'Nombre del consolidado (autol1)
            sPath = sCarpeta & "\AUTOL1"
            'Armar CintF
            Open sCarpeta & "\CINTF" For Output As #1
            Print #1, "009999990000000000000000" & sRellenar(sTratarNit(MsC02B), "0", 0, 11) & sHallarDV(MsC02B) & sRellenar(MsSucP, "0", 0, 3) & "000000000000000" & sRellenar(Val(MsNumReg) + 8, "0", 0, 5) & "000000000000000000000000000000000000000000000000000000000000000000000000000" & Space(192)
            Close #1
        Else
            sPath = sCarpeta & "\" & "IN" & MsAño & sRellenar(MsMes, "0", 0, 2) & ".txt"
        End If
        
        If Mid$(UCase(GsDsn), 1, 3) = "ORA" Then
            sFuncSub = "SubStr"
        Else
            sFuncSub = "SubString"
        End If
        
        Open sPath For Output As #1
        
        Select Case MnSGSS
            Case Salud
                MAdo.Sql = "Select " & sFuncSub & "(registros,1,255)," & sFuncSub & "(registros, 256, 58) From FCO_EPS_MM Order By secuencia"
            Case Pensiones
                MAdo.Sql = "Select " & sFuncSub & "(registros,1,255)," & sFuncSub & "(registros, 256, 13) From FCO_FPO_MM Order By secuencia"
            Case Riesgos
                MAdo.Sql = "Select " & sFuncSub & "(registros,1,255)," & sFuncSub & "(registros, 256, 8)  From FCO_ARP_MM Order By secuencia"
            Case ISS_Consolidado
                MAdo.Sql = "Select " & sFuncSub & "(registros,1,255)," & sFuncSub & "(registros, 256, 71) From FCO_ISS_MM Order By secuencia"
            Case ISS_Integrado
                MAdo.Sql = "Select " & sFuncSub & "(registros,1,255)," & sFuncSub & "(registros, 256, 74) From FCO_ISS_MM Order By secuencia"
        End Select
        
        MAdo.SendSQL
        Do Until MAdo.EOF
            Print #1, MAdo.GetField(1) & MAdo.GetField(2)
            MAdo.Mnext
        Loop
        
        Close #1
        
        If Preliminar Then
            nRetVal = Shell("NOTEPAD.EXE " & sPath, vbNormalFocus)
            If MnSGSS = ISS_Consolidado Then
                nRetVal = Shell("NOTEPAD.EXE " & sCarpeta & "\CINTI", vbNormalFocus)
                nRetVal = Shell("NOTEPAD.EXE " & sCarpeta & "\CINTF", vbNormalFocus)
            End If
        End If
    End If
    
    Screen.MousePointer = vbDefault
    Exit Sub
RutaNoExiste:
    If Err = 76 Then
        sCarpeta = "C:"
        Resume Next
    Else
        Screen.MousePointer = vbDefault
        clsMsgbox.Mensaje Err.Description, mAceptar, mAdvierte, GsTitMsg
    End If
End Sub

Private Sub GuardaCambios()
    If sprDatos.MaxRows = 0 Then Exit Sub
    Screen.MousePointer = vbHourglass
    MbRenovar = MBitacora.mActualizaBD
    MBitacora.mVaciaBuffer
    Screen.MousePointer = vbDefault
End Sub

Private Sub HallarDatosCabecera()
Dim iNumReg As Integer
    
    ResetearVariables
    
    MsC08A = ""
    
    ' ***  Nombre, NIT de la Entidad Administradora ***
    If Not MnSGSS = Riesgos Then
        MAdo.Sql = _
        " SELECT D.descripcion, A.registro_fiscal, A.digito_verificacion" & _
        " FROM datos_agr_trab D, fco_administradoras A" & _
        " WHERE D.agrupacion = A.agrupacion" & _
        "   AND D.dato = A.codigo" & _
        "   AND rtrim(A.codigo) = '" & MsDato & "'" & _
        "   AND A.tipo " & IIf(MnSGSS = Salud, "='EPS'", IIf(MnSGSS = Pensiones, "='AFP'", "IN ('EPS','AFP')"))
        MAdo.SendSQL
        If Not MAdo.EOF Then
            MsNomEnt = UCase(Trim("" & MAdo.GetField(1)))
            MsNitEnt = Trim("" & MAdo.GetField(2))
            MsDiVe = Trim("" & MAdo.GetField(3))
        End If

    End If
            
    ' ***  Datos generales del encabezado del reporte ***
    'MostrarMsg "Paso 2-01: Datos generales", Informa
    MAdo.Sql = _
    " SELECT C.nombre_cia, C.registro_fiscal, C.clase_aportante," & _
        " C.domicilio, M.nombre As nom_ciudad, C.cod_ciudad, D.nombre AS nom_dpto, C.cod_dpto," & _
        " C.telefono, C.fax, C.nro_patronal, C.NIT_ARP, C.NOMBRE_ARP, C.forma_presentacion" & _
    " FROM vw_fco_companias C," & _
        " fco_Ciudades M, fco_Departamentos D" & _
    " WHERE M.codigo = C.cod_ciudad" & _
        " AND D.codigo = C.cod_dpto" & _
        " AND M.cod_dpto = D.codigo" & _
        " AND C.compania='" & GsCveCia & "'"
    
    MAdo.SendSQL
    If Not MAdo.EOF Then
        MsC01A = UCase(Trim("" & MAdo.GetField(1))) 'nombre_cia
        MsC02A = "NIT"
        MsC02B = Trim("" & MAdo.GetField(2)) 'registro_fiscal
        MsC03A = IIf(UCase("" & MAdo.GetField(3)) = "P", "PEQUEÑO", "GRANDE") 'clase_aportante
        MsC04A = UCase(Trim("" & MAdo.GetField(4))) 'domicilio
        MsC04B = UCase(Trim("" & MAdo.GetField(5))) 'nom_ciudad
        MsC04C = Trim("" & MAdo.GetField(6)) 'cod_ciudad
        MsC04D = UCase(Trim("" & MAdo.GetField(7))) 'nom_dpto
        MsC04E = Trim("" & MAdo.GetField(8)) 'cod_dpto
        MsC04F = UCase(Trim("" & MAdo.GetField(9))) 'telefono
        MsC04G = UCase(Trim("" & MAdo.GetField(10))) 'fax
        MsC08A = IIf(UCase("" & MAdo.GetField(14)) = "U", "UNICO", IIf(UCase(MAdo.GetField(14)) = "C", "CONSOLIDADO", "SUCURSAL")) 'forma_presentacion
        MsC08B = ""
        MsSucP = "001"
        MsNroPat = Trim("" & MAdo.GetField(11)) 'nro_patronal
        If MnSGSS = Riesgos Then
            MsNomEnt = UCase(Trim("" & MAdo.GetField(13))) 'NOMBRE_ARP
            MsNitEnt = sTratarNit(Trim("" & MAdo.GetField(12))) 'NIT_ARP
            MsDiVe = sHallarDV(Trim("" & MAdo.GetField(12))) 'NIT_ARP
        End If
    End If
    
    If MsSUC <> "" Then 'Datos de encabezado por sucursal
        MsC08A = "SUCURSAL"
        MsC08B = MsSUC
        
        MAdo.Sql = _
        " SELECT C.direccion, M.nombre As nom_ciudad, C.cod_ciudad, D.nombre AS nom_dpto, C.cod_dpto," & _
            " C.telefono, C.fax, C.codigo_iss" & _
        " FROM fco_sucursales C," & _
            " fco_Ciudades M, fco_Departamentos D" & _
        " WHERE M.codigo = C.cod_ciudad" & _
            " AND D.codigo = C.cod_dpto" & _
            " AND M.cod_dpto = D.codigo" & _
            " AND C.compania='" & GsCveCia & "'" & _
            " AND RTrim(C.sucursal) ='" & RTrim(MsSUC) & "'"
    
        MAdo.SendSQL
        If Not MAdo.EOF Then
            MsC04A = UCase(Trim("" & MAdo.GetField(1))) 'direccion
            MsC04B = UCase(Trim("" & MAdo.GetField(2))) 'nom_ciudad
            MsC04C = Trim("" & MAdo.GetField(3)) 'cod_ciudad
            MsC04D = UCase(Trim("" & MAdo.GetField(4))) 'nom_dpto
            MsC04E = Trim("" & MAdo.GetField(5)) 'cod_dpto
            MsC04F = UCase(Trim("" & MAdo.GetField(6))) 'telefono
            MsC04G = UCase(Trim("" & MAdo.GetField(7))) 'fax
            MsC08B = UCase(Trim("" & MAdo.GetField(8))) 'codigo_iss
        End If

    End If
    If Trim(MsC08B) <> "" Then
        MsSucP = sRellenar(Trim(CStr(Val(MsC08B))), "0", 0, 3)
    End If
    
    MsC05A = MsAño & "  " & sRellenar(MsMes, "0", 0, 2) 'periodo actual Paga Vencido
    If MnSGSS = Salud And Trim(GsCveCia) <> "10" Then 'Bobadas de la NACH
        MsC05A = sMesSte(MsAño, MsMes) 'periodo siguiente Pago Anticipado
    End If
    
    If UCase(Left(GsDsn, 3)) = "SQL" Then
        ' CALCULO DEL NUMERO DE TRABAJADORES
        If MnSGSS = Salud Then
            MAdo.Sql = _
            " SELECT dbo.fn_fco_nro_trab_eps(" & _
            "'" & GsCveCia & "'," & _
            MsAño & "," & _
            MsMes & "," & _
            "'" & MsSUC & "')"
            MAdo.SendSQL
            If Not MAdo.EOF Then MsC09A = Trim(CStr("" & MAdo.GetField(1)))
        End If
        If MnSGSS = Pensiones Then
            MAdo.Sql = _
            " SELECT dbo.fn_fco_nro_trab_fpo(" & _
            "'" & GsCveCia & "'," & _
            MsAño & "," & _
            MsMes & "," & _
            "'" & MsSUC & "')"
            MAdo.SendSQL
            If Not MAdo.EOF Then MsC09A = Trim(CStr("" & MAdo.GetField(1)))
        End If
        If MnSGSS = Riesgos Then
            MAdo.Sql = _
            " SELECT dbo.fn_fco_nro_trab_arp(" & _
            "'" & GsCveCia & "'," & _
            MsAño & "," & _
            MsMes & "," & _
            "'" & MsSUC & "')"
            MAdo.SendSQL
            If Not MAdo.EOF Then MsC09A = Trim(CStr("" & MAdo.GetField(1)))
        End If
    Else
        ' CALCULO DEL NUMERO DE TRABAJADORES
        If MnSGSS = Salud Then
            MAdo.Sql = _
            " SELECT fn_fco_nro_trab_eps(" & _
            "'" & GsCveCia & "'," & _
            MsAño & "," & _
            MsMes & "," & _
            "'" & MsSUC & "') FROM dual"
            MAdo.SendSQL
            If Not MAdo.EOF Then MsC09A = Trim(CStr("" & MAdo.GetField(1)))
        End If
        If MnSGSS = Pensiones Then
            MAdo.Sql = _
            " SELECT fn_fco_nro_trab_fpo(" & _
            "'" & GsCveCia & "'," & _
            MsAño & "," & _
            MsMes & "," & _
            "'" & MsSUC & "') FROM dual"
            MAdo.SendSQL
            If Not MAdo.EOF Then MsC09A = Trim(CStr("" & MAdo.GetField(1)))
        End If
        If MnSGSS = Riesgos Then
            MAdo.Sql = _
            " SELECT fn_fco_nro_trab_arp(" & _
            "'" & GsCveCia & "'," & _
            MsAño & "," & _
            MsMes & "," & _
            "'" & MsSUC & "') FROM dual"
            MAdo.SendSQL
            If Not MAdo.EOF Then MsC09A = Trim(CStr("" & MAdo.GetField(1)))
        End If
      
    End If
            
'    If MnSGSS <> ISS_Consolidado And MnSGSS <> Riesgos Then
'        ' ***  Numero Total de Empleados ***
'        Mado.SQL = _
'        " SELECT Count(COD_TRAB) FROM " & MsTabla & _
'        IIf(MsSuc = "", "", " WHERE COD_SUC='" & MsSuc & "'")
'        Mado.SendSQL
'        If Not Mado.EOF Then MsC09A = Trim(CStr("" & Mado.GetField(1)))
'    End If
    
'    If MnSGSS = Riesgos Then
'        Mado.SQL = _
'        " SELECT Count(COD_TRAB) FROM " & MsTabla & _
'        IIf(MsSuc = "", "", " WHERE COD_SUC='" & MsSuc & "'") & _
'        IIf(MsSuc = "", " WHERE ", " AND ") & _
'        " (C29A > 0 OR C13F = 'X' OR C13G = 'X' OR C13H = 'X' OR C13I = 'X' OR C13K > 0)"
'        Mado.SendSQL
'        If Not Mado.EOF Then MsC09A = Trim(CStr("" & Mado.GetField(1)))
'    End If
    
    If MnSGSS = Salud Or MnSGSS = Pensiones Then
        ' ***  Numero de Afiliados ***
        MAdo.Sql = _
        " SELECT COD_TRAB T" & _
        " FROM " & MsTabla & _
        " WHERE " & IIf(MnSGSS = Salud, "COD_EPS", "COD_FPO") & "='" & MsDato & "'" & _
        IIf(MsSUC = "", "", " And COD_SUC='" & MsSUC & "'") & _
        " GROUP BY COD_TRAB" & _
        " HAVING SUM(" & IIf(MnSGSS = Salud, "C24A", "C19A") & ")>0"
        MAdo.SendSQL
        
        iNumReg = 0
        While Not MAdo.EOF
            iNumReg = iNumReg + 1
            MAdo.Mnext
        Wend
        MsC10A = iNumReg
    End If
    If MnSGSS = ISS_Consolidado Then
        ' ***  Numero de Registros ***
        iNumReg = 0
        MAdo.Sql = _
        " SELECT COD_TRAB T" & _
        " FROM " & MsTabla & _
        IIf(MsSUC = "", "", " WHERE RTrim(COD_SUC)='" & RTrim(MsSUC) & "'") & _
        " GROUP BY COD_TRAB" & _
        " HAVING SUM(C14A+C14C)>0"
        MAdo.SendSQL
        MsNumReg = ""
        While Not MAdo.EOF
            iNumReg = iNumReg + 1
            MAdo.Mnext
        Wend
        MsNumReg = iNumReg
                
        ' ***  Numero de Afiliados en Pension ***

        iNumReg = 0
        MAdo.Sql = _
        " SELECT COD_TRAB T" & _
        " FROM " & MsTabla & _
        " WHERE COD_FPO='" & IIf(Trim(GsCveCia) = "10", "2501", "ISS") & "'" & _
        IIf(MsSUC = "", "", " And RTrim(COD_SUC)='" & RTrim(MsSUC) & "'") & _
        " GROUP BY COD_TRAB" & _
        " HAVING SUM(C14A)>0"
        MAdo.SendSQL
        
        While Not MAdo.EOF
            iNumReg = iNumReg + 1
            MAdo.Mnext
        Wend
        
        MsC09B = iNumReg
        
        ' ***  Numero de Afiliados en Salud ***

        iNumReg = 0
        MAdo.Sql = _
        " SELECT COD_TRAB T" & _
        " FROM " & MsTabla & _
        " WHERE COD_EPS='" & IIf(Trim(GsCveCia) = "10", "006", "ISS") & "'" & _
        IIf(MsSUC = "", "", " And RTrim(COD_SUC)='" & RTrim(MsSUC) & "'") & _
        " GROUP BY COD_TRAB" & _
        " HAVING SUM(C14C)>0"
        MAdo.SendSQL
        
        While Not MAdo.EOF
            iNumReg = iNumReg + 1
            MAdo.Mnext
        Wend
        MsC09C = iNumReg
        
    End If
    If MnSGSS = ISS_Integrado Then
        
        ' ***  Numero de Registros ***
        iNumReg = 0
        MAdo.Sql = _
        " SELECT COD_TRAB T" & _
        " FROM " & MsTabla & _
        IIf(MsSUC = "", "", " WHERE COD_SUC='" & MsSUC & "'") & _
        " GROUP BY COD_TRAB" & _
        " HAVING SUM(C32+C38)>0"
        MAdo.SendSQL
        MsNumReg = ""
        
        While Not MAdo.EOF
            iNumReg = iNumReg + 1
            MAdo.Mnext
        Wend
        
        MsNumReg = iNumReg
                
        ' ***  Numero de Afiliados en Pension ***
        iNumReg = 0
        MAdo.Sql = _
        " SELECT COD_TRAB T" & _
        " FROM " & MsTabla & _
        " WHERE COD_FPO='ISS'" & _
        IIf(MsSUC = "", "", " And COD_SUC='" & MsSUC & "'") & _
        " GROUP BY COD_TRAB" & _
        " HAVING SUM(C32)>0"
        MAdo.SendSQL
        
        While Not MAdo.EOF
            iNumReg = iNumReg + 1
            MAdo.Mnext
        Wend
        
        MsC09B = iNumReg
                
        ' ***  Numero de Afiliados en Salud ***
        iNumReg = 0
        
        MAdo.Sql = _
        " SELECT COD_TRAB T" & _
        " FROM " & MsTabla & _
        " WHERE COD_EPS='ISS'" & _
        IIf(MsSUC = "", "", " And COD_SUC='" & MsSUC & "'") & _
        " GROUP BY COD_TRAB" & _
        " HAVING SUM(C38)>0"
        MAdo.SendSQL
        
        While Not MAdo.EOF
            iNumReg = iNumReg + 1
            MAdo.Mnext
        Wend
        
        MsC09C = iNumReg
        
    End If

End Sub

Private Sub HallarDatosPie()
    Dim i As Integer
    Dim nSec As Byte
    
    For i = 20 To 28
        crptReport.Formulas(i) = ""
        crptReport.Formulas(i + 10) = ""
        crptReport.Formulas(i + 20) = ""
        crptReport.Formulas(i + 30) = ""
        If MnSGSS = ISS_Consolidado Then crptReport.Formulas(i + 30) = ""
    Next i
    MAdo.Sql = _
    " SELECT B.secuencia, Max(" & MsEsNulo & "(A.referencia,'')) referencia," & _
    " Sum(" & MsEsNulo & "(A.valor_1,0)) valor_1, Sum(" & MsEsNulo & "(A.valor_2,0)) valor_2," & _
    " Sum(" & MsEsNulo & "(A.valor_3,0)) valor_3" & _
    " FROM fco_ala_datos_adi A, fco_rel_sgss_da B" & _
    " WHERE A.sgss = B.sgss and A.item = B.ala_datos_adi" & _
    " AND RTrim(A.tabla)='" & RTrim(MsTabla) & "'" & _
    " AND RTrim(A.cod_adm)='" & RTrim(MsDato) & "'" & _
    IIf(Trim(MsSUC) <> "", " AND " & MsEsNulo & "(RTrim(A.cod_suc)" & IIf(Left(UCase(GsDsn), 3) = "ORA", "||", "+") & "'0','0')='" & RTrim(MsSUC) & "0'", "") & _
    " GROUP BY B.secuencia"
    MAdo.SendSQL
    
    Do Until MAdo.EOF
        nSec = Val("" & MAdo.GetField(1)) 'secuencia
        If "" & MAdo.GetField(2) <> "" Then  'referencia
            crptReport.Formulas(20 + nSec) = "da1_" & nSec & "='" & MAdo.GetField(2) & "'"
        End If
        If Val("" & MAdo.GetField(3)) <> 0 Then  'valor_1
            crptReport.Formulas(30 + nSec) = "da2_" & nSec & "=" & MAdo.GetField(3)
        End If
        If Val("" & MAdo.GetField(4)) <> 0 Then  'valor_2
            crptReport.Formulas(40 + nSec) = "da3_" & nSec & "=" & MAdo.GetField(4)
        End If
        If MnSGSS = ISS_Consolidado Then
            If Val("" & MAdo.GetField(5)) <> 0 Then  'valor_3
                crptReport.Formulas(50 + nSec) = "da4_" & nSec & "=" & MAdo.GetField(5)
                Clipboard.Clear
                Clipboard.SetText "da4_" & nSec
            End If
        End If
        MAdo.Mnext
    Loop
End Sub

Private Sub HallarOrden()
  crptReport.Formulas(60) = ""

  'si no es el reporte de consolidado
  If Not MnSGSS = ISS_Consolidado Then
      If MsOrdenRep = "A" Then
         crptReport.Formulas(60) = "AGRUPAMIENTO = {@DEF_NOMBRE_COMPLETO}"
      Else
         crptReport.Formulas(60) = "AGRUPAMIENTO = {@C11B}"
      End If
  Else
      If MsOrdenRep = "A" Then
         crptReport.Formulas(60) = "AGRUPAMIENTO1 = {@DEF_10D_APELLIDO+NOMBRE}+{@DEF_10B_NUMERO_DOCUMENTO}"
      Else
         crptReport.Formulas(60) = "AGRUPAMIENTO1 = {@DEF_10B_NUMERO_DOCUMENTO}"
      End If
  End If
    
End Sub

Private Sub HallarSistema(Fila As Integer)
    sprDatos.Row = Fila
    sprDatos.Col = 2
    
    MsRuta = ""
    MAdo.Sql = _
    " SELECT maneja_EPS, maneja_FPO, ISS_Integrado, maneja_SUC," & _
    " ruta_rep, maneja_mm, ruta_mm, maneja_ARP, maneja_ISS, orden" & _
    " FROM fco_Reportes_ALA" & _
    " WHERE Codigo = '" & sprDatos.Text & "'"
    MAdo.SendSQL

    If Not MAdo.EOF Then
        With sprDatos
            .Col = 4: MsAño = Trim(.Text)
            .Col = 5: MsMes = Val(.Text)
            .Col = 6: MsDato = Trim(.Text)
            .Col = 7: MsSUC = Trim(.Text)
        End With
        If Val("" & MAdo.GetField(1)) = 1 Then MnSGSS = Salud
        If Val("" & MAdo.GetField(2)) = 1 Then MnSGSS = Pensiones
        If Val("" & MAdo.GetField(8)) = 1 Then MnSGSS = Riesgos
        If Val("" & MAdo.GetField(9)) = 1 Then
            MnSGSS = IIf(Val("" & MAdo.GetField(3)) = 1, ISS_Integrado, ISS_Consolidado)
        End If
        MbMedioMagnetico = IIf(Val("" & MAdo.GetField(6)) = 0, False, True)
        If MbMedioMagnetico Then
            MsRuta = "" & MAdo.GetField(7)
        Else
            MsRuta = "" & MAdo.GetField(5)
        End If
        
        MsOrdenRep = "" & MAdo.GetField(10)
    End If
    MsTabla = MsCalif
    Select Case MnSGSS
        Case Salud: MsTabla = "FCO_EPS_"
        Case Pensiones: MsTabla = "FCO_FPO_"
        Case Riesgos: MsTabla = "FCO_ARP_"
        Case ISS_Consolidado: MsTabla = "FCO_VW_ISS_"
        Case ISS_Integrado: MsTabla = "FCO_ISS_"
    End Select
    MsTabla = MsTabla & Trim(GsCveCia) & "_" & MsAño & "_" & MsMes
End Sub

Private Function iDeseaGuardarCambios() As Integer
    ' Descripción : Devuelve el valor de la opción seleccionada en la clsMsgBox
    ' Uso : iDeseaGuardarCambios
    ' Regresa : Un Entero , dependiendo de la respuesta en clsMsgBox
    If MBitacora.pTransActual > 0 Then
       iDeseaGuardarCambios = clsMsgbox.Mensaje("¿Desea guardar los cambios?", mSiNoCancelar, mConfirma, GsTitMsg)
       Select Case iDeseaGuardarCambios
          Case 6
             GuardaCambios
             If MbRenovar = 0 Then iDeseaGuardarCambios = 2
          Case 7
             MBitacora.mVaciaBuffer 'Vacía el Buffer de la Bitácora
       End Select
    Else
        iDeseaGuardarCambios = 1
    End If
End Function

Private Sub OrdenarDatos()
    Screen.MousePointer = vbHourglass
    If MsAntOrden = CStr(sprDatos.ActiveCol) Then
        MbOrdenAsc = Not (MbOrdenAsc)
    Else
        MbOrdenAsc = True
    End If
    MsOrden = " Order By " & CStr(sprDatos.ActiveCol) & IIf(MbOrdenAsc, "", "DESC")
    MsAntOrden = CStr(sprDatos.ActiveCol)
    RenuevaDatos
    Screen.MousePointer = vbDefault
    
End Sub

Private Sub Procesar()
    Dim i As Integer
    Dim BNada As Boolean
    
    Screen.MousePointer = vbHourglass
    FCO5010P.pgbPorc.Value = 0
    FCO5010P.Show
    DoEvents
    
    BNada = True
    For i = 1 To sprDatos.MaxRows
        FCO5010P.pgbPorc.Value = ((i - 1) * 100) \ sprDatos.VirtualMaxRows
        FCO5010P.lblPorc = CStr(FCO5010P.pgbPorc.Value) & " %"
        DoEvents
        sprDatos.Row = i
        sprDatos.Col = 1
        If Val(sprDatos.Value) = 1 Then BNada = False: GenerarReporte i, crptToPrinter, False
    Next i
    
    Unload FCO5010P
    Screen.MousePointer = vbDefault
    If BNada Then clsMsgbox.Mensaje "No hay nada para procesar." & vbCrLf & vbCrLf & "Debe seleccionar las filas que quiere procesar.", mAceptar, mAdvierte, GsTitMsg

End Sub

Private Sub RenovarDatos()
  MiKey = vbKeyReturn
  AplicaFiltros

End Sub

Private Sub RenuevaDatos()
    ConfiguraSpread
    MsSql = " SELECT procesar, codigo, nombre, anio, mes, EPS_FPO, sucursal, secuencia, descripcion" & _
            " FROM vw_fco_proc_reportes_ala V" & _
            " WHERE compania = '" & GsCveCia & "'" & _
            " And EXISTS (SELECT 1 FROM vw_fco_sucursales_cia WHERE V.compania = compania and " & _
            MsEsNulo & "(LTrim(RTrim(V.sucursal)), '') = " & MsEsNulo & "(LTrim(RTrim(sucursal)), '') and" & _
            " (clase_nomina='--' OR" & _
            " clase_nomina in (SELECT clase_nomina FROM rel_usu_clase_nom WHERE usuario = '" & GsUid & "')))" & _
            MsWhereAdi & _
            " UNION" & _
            " SELECT procesar, codigo, nombre, anio, mes, EPS_FPO, sucursal, secuencia, descripcion" & _
            " FROM vw_fco_proc_reportes_ala" & _
            " WHERE compania = '" & GsCveCia & "' and" & _
            " (sucursal is null OR ltrim(rtrim(sucursal)) = '')" & _
            MsWhereAdi

    MAdo.Sql = MsSql & MsOrden
    If Not MAdo.SendSQL Then Exit Sub
    clsSpread.LlenaSpread 0, sprDatos, MAdo, MAdo.lhDbc, MAdo.lhstmt
        
    With sprDatos
        .ColWidth(1) = 2
        .ColWidth(2) = 7
        .ColWidth(3) = 27
        .ColWidth(4) = 5.5
        .ColWidth(5) = 5.5
        .ColWidth(6) = 6.5
        .ColWidth(7) = 6.5
        .ColWidth(8) = 0
        .ColWidth(9) = 0
        .Col = 1: .Row = -1: .CellType = 10
        .Col = 2: .Row = -1: .Lock = True
        .Col = 3: .Row = -1: .Lock = True
        .Col = 4: .Row = -1: .Lock = True
        .Col = 5: .Row = -1: .Lock = True
        .Col = 6: .Row = -1: .Lock = True
        .Col = 7: .Row = -1: .Lock = True
        .Col = 8: .Row = -1: .Lock = True
        .Col = 9: .Row = -1: .Lock = True
        .Col = 4: .CellType = 3
        .Col = 5: .CellType = 3
        .ScrollBars = ScrollBarsBoth
        .Visible = True
    End With
End Sub

Private Sub AplicaFiltros()
    MsWhereAdi = ""
                    
    If Val(txtAnio) <> 0 Then
      Select Case MiKey
          Case vbKeyReturn
              MsWhereAdi = " AND anio = " & txtAnio & ""
          Case 10
              MsWhereAdi = " AND anio = " & txtAnio & ""
      End Select
    End If
    
    If Val(txtMes) <> 0 Then
      Select Case MiKey
          Case vbKeyReturn
              MsWhereAdi = MsWhereAdi & " AND mes = " & txtMes & ""
          Case 10
              MsWhereAdi = MsWhereAdi & " AND mes = " & txtMes & ""
      End Select
    End If
    
    If Trim(txtReporte) <> "" Then
        Select Case MiKey
            Case vbKeyReturn
                MsWhereAdi = MsWhereAdi & " AND codigo Like '%" & txtReporte & "%'"
            Case 10
                MsWhereAdi = MsWhereAdi & " AND codigo Like '" & txtReporte & "%'"
        End Select
    End If

    If Trim(txtNomRep) <> "" Then
        Select Case MiKey
            Case vbKeyReturn
                MsWhereAdi = MsWhereAdi & " AND nombre Like '%" & txtNomRep & "%'"
            Case 10
                MsWhereAdi = MsWhereAdi & " AND nombre Like '" & txtNomRep & "%'"
        End Select
    End If

    If Trim(txtAdm) <> "" Then
        Select Case MiKey
            Case vbKeyReturn
                MsWhereAdi = MsWhereAdi & " AND EPS_FPO Like '%" & txtAdm & "%'"
            Case 10
                MsWhereAdi = MsWhereAdi & " AND EPS_FPO Like '" & txtAdm & "%'"
        End Select
    End If

    If Trim(txtSucursal) <> "" Then
        Select Case MiKey
            Case vbKeyReturn
                MsWhereAdi = MsWhereAdi & " AND sucursal Like '%" & txtSucursal & "%'"
            Case 10
                MsWhereAdi = MsWhereAdi & " AND sucursal Like '" & txtSucursal & "%'"
        End Select
    End If

    RenuevaDatos
End Sub

Private Sub ResetearVariables()
    'Entidad Administradora
    MsNomEnt = ""
    MsNitEnt = ""
    MsDiVe = ""
    
    'Encabezado Reportes
    MsC01A = ""    'Razón social
    MsC02A = ""    'NIT/CC/CE
    MsC02B = ""    'Numero Id
    MsC03A = ""    'Clase de Aportante P/G
    MsC04A = ""    'Direccion
    MsC04B = ""    'Nombre Ciudad
    MsC04C = ""    'Codigo Ciudad
    MsC04D = ""    'Nombre Departamento
    MsC04E = ""    'Codigo Departamento
    MsC04F = ""    'Telefono
    MsC04G = ""    'Fax
    MsC05A = ""    'Periodo de cotizacion
    MsC08A = ""    'Forma de presentacion U/C/S
    MsC08B = ""    'Codigo sucursal
    MsC09A = ""    'Nro total de trabajadores (o de afiliados al ISS ne Riesgos)
    MsC09B = ""    'Nro de afiliados al ISS en Pension
    MsC09C = ""    'Nro de afiliados al ISS en Salud
    MsC10A = ""    'Nro de afiliados
End Sub

Private Sub TrabajarCon()
    If sprDatos.VirtualMaxRows > 0 Then
      Screen.MousePointer = vbHourglass
      With sprDatos
          HallarSistema .ActiveRow
          .Row = .ActiveRow
          .Col = 6
          GsAdmin = Trim(.Text) 'Codigo de la Administradora
          .Col = 7
          GsCodDato = Trim(.Text) 'Sucursal
      End With
      GnSGSS = MnSGSS 'Sistema de S.S.
      GsTabla = Trim(MsTabla) 'Nombre de la tabla que contiene (o contendrá) los datos
      FCO5010T.Show 1
    End If
End Sub

Private Sub txtAdm_KeyPress(KeyAscii As Integer)
    If KeyAscii <> vbKeyReturn And KeyAscii <> 10 Then Exit Sub
    MiKey = KeyAscii
    AplicaFiltros

End Sub

Private Sub txtAnio_KeyPress(KeyAscii As Integer)
    If KeyAscii <> vbKeyReturn And KeyAscii <> 10 Then Exit Sub
    MiKey = KeyAscii
    AplicaFiltros
End Sub

Private Sub txtMes_KeyPress(KeyAscii As Integer)
    If KeyAscii <> vbKeyReturn And KeyAscii <> 10 Then Exit Sub
    MiKey = KeyAscii
    AplicaFiltros

End Sub

Private Sub txtNomRep_KeyPress(KeyAscii As Integer)
    If KeyAscii <> vbKeyReturn And KeyAscii <> 10 Then Exit Sub
    MiKey = KeyAscii
    AplicaFiltros

End Sub

Private Sub txtReporte_KeyPress(KeyAscii As Integer)
    If KeyAscii <> vbKeyReturn And KeyAscii <> 10 Then Exit Sub
    MiKey = KeyAscii
    AplicaFiltros

End Sub

Private Sub txtSucursal_KeyPress(KeyAscii As Integer)
    If KeyAscii <> vbKeyReturn And KeyAscii <> 10 Then Exit Sub
    MiKey = KeyAscii
    AplicaFiltros

End Sub
