Advertisement
szisziPicaxu

frmHistorico

Apr 13th, 2023
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VBScript 10.86 KB | Software | 0 0
  1.  
  2. '******************************************************************************'
  3. ' Project    : Sanepar
  4. ' Author     : leandro.pedro@intech-automacao.com.br
  5. ' File       : frmHistory.frm
  6. ' Date       : 2019.03.13
  7. ' FormVersion: 0.0.5
  8. '
  9. ' Revision history
  10. '------------------------------------------------------------------------------'
  11. ' Date      Author  Revision
  12. ' 19.03.18  lbp     Adicionado filtro.
  13. ' 19.03.19  lbp     Corrigido caminho para pasta \ALM configurada no SCU.
  14. '------------------------------------------------------------------------------'
  15. ' Copyright (c) 2018 by In-Tech Automacao & Sistemas. All Rights Reserved.
  16. '******************************************************************************'
  17. Option Explicit
  18. '
  19. ' Cria browse dialog.
  20. ' @save_as {boolean} savar como ou abrir.
  21. ' @custom_filter {string} filtro tipo de arquivo.
  22. '
  23. Private Function Dialog( _
  24.         Optional ByVal save_as As Boolean = False, _
  25.         Optional ByVal custom_filter As String = "All Files (*.*)|*.*|") As String
  26.    
  27.     Dim dlgCommonDialog
  28.     Set dlgCommonDialog = CreateObject("MSComDlg.CommonDialog")
  29.     With dlgCommonDialog
  30.         .CancelError = False
  31.         .Filter = custom_filter
  32.         If save_as Then
  33.             .ShowSave
  34.         Else
  35.             .ShowOpen
  36.         End If
  37.     End With
  38.     Dialog = dlgCommonDialog.filename
  39. End Function
  40. '
  41. ' Retorna dd/MM/yy
  42. ' @param {string} nome do arquivo yyMMdd.ALM
  43. '
  44. Function FormatFileNameToDate(filename As String) As String
  45.     FormatFileNameToDate = Mid(filename, 5, 2) & "/" & Mid(filename, 3, 2) & "/" & Mid(filename, 1, 2)
  46. End Function
  47. '
  48. ' Retorna yymmdd.ALM
  49. ' @param {string} data dd/MM/yy
  50. '
  51. Function FormatDateToFileName(strDate As String) As String
  52.     If strDate <> "" Then
  53.         FormatDateToFileName = Mid(strDate, 7, 2) & Mid(strDate, 4, 2) & Mid(strDate, 1, 2) & ".ALM"
  54.     End If
  55. End Function
  56. '
  57. ' Retorna array com os arquivos contidos na pasta \ALM com ou sem filtro.
  58. ' @param {string} filtro por tipo de arquivo.
  59. '
  60. Private Function GetFiles(Optional Filter As String = "*.*") As Variant
  61.     Dim arr
  62.     Dim Path As String
  63.     Dim strFile As String
  64.     'Dim list As Object
  65.    'Set list = CreateObject("System.Collections.ArrayList")
  66.    arr = Array()
  67.  
  68.     Path = System.FixPath(12) & "\"
  69.     strFile = Dir(Path & Filter)
  70.    
  71.     Do While (strFile <> vbNullString)
  72.         'list.Add str_file
  73.        ReDim Preserve arr(0 To UBound(arr) + 1)
  74.         arr(UBound(arr)) = strFile
  75.         strFile = Dir
  76.     Loop
  77.     'list.Sort
  78.    'list.Reverse
  79.    GetFiles = arr  'listoArray
  80. End Function
  81.  
  82. '
  83. ' Filter
  84. '
  85. Private Sub btnFilter_Click()
  86.     PopulateList True
  87. End Sub
  88.  
  89. '
  90. ' Combobox
  91. '
  92. Private Sub cboFile_Change()
  93.     PopulateList
  94. End Sub
  95. Private Sub PopulateList(Optional Filtered As Boolean = False)
  96.     Dim c As New Cursor
  97.     Dim match As Boolean
  98.     Dim regex As Object
  99.     Dim str_file As String
  100.     Dim txt_line As String
  101.     Dim Path As String
  102.    
  103.     Path = System.FixPath(12) & "\"
  104.     str_file = FormatDateToFileName(cboFile)
  105.        
  106.     If str_file = "" Then Exit Sub
  107.    
  108.     lvwAlarm.ListItems.Clear
  109.     lvwEvent.ListItems.Clear
  110.    
  111.     Open (Path & str_file) For Input As #1
  112.    
  113.     Do Until EOF(1)
  114.         Line Input #1, txt_line
  115.         c.Init txt_line
  116.        
  117.         If txtTagName = "" Then txtTagName = "*"
  118.         If txtMessage = "" Then txtMessage = "*"
  119.        
  120.         If c.sTime <> "" Then
  121.             match = IIf(Not Filtered, True, _
  122.                     ((LCase(c.sTagname) Like LCase(txtTagName)) Or c.IsEvent) And _
  123.                     LCase(c.sDescription) Like LCase(txtMessage) And _
  124.                     TimeValue(c.sTime) >= TimeValue(dtStartTime) And _
  125.                     TimeValue(c.sTime) <= TimeValue(dtEndTime))
  126.            
  127.             If (match) Then
  128.                 Select Case c.IsEvent
  129.                     Case True   ' Lista de eventos.
  130.                        With lvwEvent.ListItems.Add()
  131.                             .Text = c.sDate
  132.                             .SubItems(1) = c.sTime
  133.                             .SubItems(2) = c.sDescription
  134.                         End With
  135.                     Case False  ' Lista de alarmes.
  136.                        With lvwAlarm.ListItems.Add()
  137.                             .Text = c.sDate
  138.                             .SubItems(1) = c.sTime
  139.                             .SubItems(2) = c.sTagname
  140.                             .SubItems(3) = c.sType
  141.                             .SubItems(4) = c.sValue
  142.                             .SubItems(5) = c.sDescription
  143.                         End With
  144.                 End Select
  145.             End If
  146.         End If
  147.     Loop
  148.    
  149.     Close #1
  150. End Sub
  151.  
  152. Private Sub chkFilter_Click()
  153.     PopulateList chkFilter.Value
  154. End Sub
  155.  
  156. '
  157. ' Ordenar lista de alarmes.
  158. '
  159. Private Sub lvwAlarm_ColumnClick(ByVal ColumnHeader As MSComctlLib.ColumnHeader)
  160.     With lvwAlarm
  161.         .SortKey = ColumnHeader.Index - 1
  162.         .SortOrder = (.SortOrder - 1) * -1
  163.         .Sorted = True
  164.     End With
  165. End Sub
  166. '
  167. ' Ordenar lista de eventos.
  168. '
  169. Private Sub lvwEvent_ColumnClick(ByVal ColumnHeader As MSComctlLib.ColumnHeader)
  170.     With lvwEvent
  171.         .SortKey = ColumnHeader.Index - 1
  172.         .SortOrder = (.SortOrder - 1) * -1
  173.         .Sorted = True
  174.     End With
  175. End Sub
  176. '
  177. ' Multipage mudanca de aba.
  178. '
  179. Private Sub multiPage_Change()
  180.     lblTagName.Enabled = (multiPage.Value = 0)
  181.     txtTagName.Enabled = (multiPage.Value = 0)
  182. End Sub
  183.  
  184. '
  185. ' Activate
  186. '
  187. Private Sub UserForm_Initialize()
  188.    
  189.     CentralizeForm
  190.  
  191.     ' Cria nome das colunas de alarme.
  192.    With lvwAlarm
  193.         .View = lvwReport
  194.         .ColumnHeaders.Add , , "Data", 60
  195.         .ColumnHeaders.Add , , "Hora", 60
  196.         .ColumnHeaders.Add , , "Nome do tag", 120
  197.         .ColumnHeaders.Add , , "Tipo", 60
  198.         .ColumnHeaders.Add , , "Valor", 60
  199.         .ColumnHeaders.Add , , "Mensagem", 196
  200.         .FullRowSelect = True
  201.     End With
  202.    
  203.     ' Cria nome das colunas de eventos.
  204.    With lvwEvent
  205.         .View = lvwReport
  206.         .ColumnHeaders.Add , , "Data", 60
  207.         .ColumnHeaders.Add , , "Hora", 60
  208.         .ColumnHeaders.Add , , "Mensagem", 436
  209.         .FullRowSelect = True
  210.     End With
  211.    
  212.     ' Preenche combox.
  213.    cboFile.Clear
  214.     Dim itm As Variant
  215.     For Each itm In GetFiles("*.alm")
  216.         cboFile.AddItem FormatFileNameToDate(CStr(itm))
  217.     Next
  218. End Sub
  219. '
  220. ' Close
  221. '
  222. Private Sub btnClose_Click()
  223.     Unload Me
  224. End Sub
  225. '
  226. ' Export
  227. '
  228. Private Sub btnExport_Click()
  229.     Const xlCellTypeVisible = 12
  230.     Const xlCenter = -4108
  231.     Const xlToLeft = -4159
  232.    
  233.     Dim excel_app As Object
  234.     Dim workbook As Variant
  235.     Dim sht As Variant
  236.     Dim itmX As Variant, itmY As Variant
  237.     Dim last_col As Integer, last_row As Integer
  238.     Dim lvw As Object
  239.        
  240.     Select Case multiPage.Value
  241.         Case 0: Set lvw = lvwAlarm  ' Aba alarmes.
  242.        Case 1: Set lvw = lvwEvent  ' Aba eventos.
  243.    End Select
  244.    
  245.     On Error GoTo ErrorHandler
  246.     If lvw.ListItems.Count > 0 Then
  247.         Set excel_app = CreateObject("Excel.Application")
  248.         Set workbook = excel_app.Workbooks.Add(1)
  249.        
  250.         ' Nomeia planilha.
  251.        Set sht = workbook.Sheets.Item(1)
  252.         sht.Name = lvw.Parent.Caption
  253.        
  254.         ' Linha/coluna incial.
  255.        Dim row As Integer: row = 5
  256.         Dim col As Integer: col = 1
  257.        
  258.         last_col = lvw.ColumnHeaders.Count - 1
  259.        
  260.         ' Adiciona linha com título e mescla.
  261.        With sht.Cells(row, col)
  262.             .Value = "HISTÓRICO DE " & UCase(lvw.Parent.Caption)
  263.             .Font.Bold = True
  264.             .HorizontalAlignment = xlCenter
  265.         End With
  266.         sht.range(sht.Cells(row, 1), sht.Cells(row, last_col)).Merge
  267.         row = row + 2
  268.        
  269.         ' Adiciona linha com data.
  270.        With sht.Cells(row, col)
  271.             .Value = "Data:"
  272.             .Font.Bold = True
  273.         End With
  274.         sht.Cells(row, col + 1).Value = "'" & cboFile.Text
  275.         row = row + 2
  276.        
  277.         ' Estiliza cabecalho.
  278.        With sht.range(sht.Cells(1, 1), sht.Cells(row, last_col))
  279.             .Interior.Color = vbWhite
  280.             .Font.Color = vbBlue
  281.         End With
  282.        
  283.         ' Cria linha com titulo das colunas.
  284.        For col = 1 To last_col
  285.             sht.Cells(row, col).Value = lvw.ColumnHeaders(col + 1).Text
  286.         Next
  287.        
  288.         ' Estiliza linha com titulos das colunas.
  289.        With sht.range(sht.Cells(row, 1), sht.Cells(row, last_col))
  290.             .Interior.Color = vbBlue 'RGB(48, 89, 155)
  291.            .Font.Color = vbWhite
  292.             .Font.Bold = True
  293.             .Columns.AutoFilter
  294.             ' .Columns.AutoFit
  295.        End With
  296.  
  297.         ' Preenche planilha com dados conforme sort e filtro da lista.
  298.        For Each itmX In lvw.ListItems
  299.             col = 1
  300.             row = row + 1
  301.             For Each itmY In itmX.ListSubItems
  302.                 sht.Cells(row, col).Value = itmY
  303.                 col = col + 1
  304.             Next
  305.         Next
  306.        
  307.         ' Ajusta largura das colunas.
  308.        sht.Cells.SpecialCells(xlCellTypeVisible).EntireColumn.AutoFit
  309.  
  310.         ' Adiciona logo sanepar.
  311.        With sht.Pictures.Insert(System.DocumentPath & "\logo.png")
  312.             .Left = 0
  313.             .Top = 0
  314.         End With
  315.            
  316.         Dim file As String
  317.         file = Dialog(True, "Excel Workbook (*.xlsx), *.xlsx")
  318.  
  319.         ' Salva e fecha objeto excel.
  320.        If (file <> "") Then
  321.             workbook.SaveAs file
  322.             If MsgBox("Deseja abrir o arquivo gerado?", vbYesNo) = vbYes Then
  323.                 Shell excel_app.Path & "\Excel.exe" & " " & file, vbMaximizedFocus
  324.             End If
  325.         End If
  326.                
  327.         workbook.Close SaveChanges:=False
  328.         excel_app.Quit
  329.     End If
  330.  
  331.     Exit Sub
  332.    
  333. ErrorHandler:
  334.     MsgBox Err.Description, vbExclamation
  335.     workbook.Close SaveChanges:=False
  336.     excel_app.Quit
  337. End Sub
  338.  
  339. '
  340. ' CentralizeForm
  341. '
  342. Private Sub CentralizeForm()
  343.     Dim ID As Integer
  344.     Dim X As Double
  345.     Dim Y As Double
  346.     Dim pt As POINTAPI
  347.    
  348.     GetCursorPos pt
  349.    
  350.     On Error GoTo ErrorHandler:
  351.    
  352.     ' Retorna resolucao width x height px do monitor onde o mouse esta posicionado.
  353.    X = GetSystemMetrics(0)
  354.     Y = GetSystemMetrics(1)
  355.    
  356.     ID = IIf(pt.X > X, 2, 1)
  357.    
  358.     ' Posicao manual do form.
  359.    Me.StartUpPosition = 0
  360.  
  361.     ' Transforma px em ppi, unidade de medida utilizada pelo UserForm.
  362.    X = (PixelsToPoints(X) / 2) + ((ID - 1) * PixelsToPoints(X))
  363.     Y = (PixelsToPoints(Y) / 2)
  364.    
  365.     ' Posiciona o form para abrir centralizado na tela chamadora.
  366.    Me.Left = CSng(X) - Me.width / 2
  367.     Me.Top = CSng(Y) - Me.Height / 2
  368.    
  369.     Exit Sub '
  370. ErrorHandler:
  371.     Debug.Print Err, Err.Description
  372.     Select Case Err
  373.         Case -2147200630, 91
  374.             ID = 2
  375.             Resume Next
  376.     End Select
  377. End Sub
  378.  
  379.  
  380.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement