Advertisement
ficho2604

Untitled

Apr 18th, 2023
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 25.41 KB | None | 0 0
  1. Imports System.IO
  2. Imports System.Runtime.InteropServices
  3. Imports System.Text
  4. Imports System.Windows.Forms
  5. Imports Excel = Microsoft.Office.Interop.Excel
  6.  
  7. Public Class Form1
  8.     Private savedFilePaths As New Dictionary(Of String, String)()
  9.     Private folderPaths As New Dictionary(Of String, String)()
  10.     Private fileDict As New Dictionary(Of String, String)()
  11.     Private excelDataCache As New Dictionary(Of String, List(Of List(Of String)))()
  12.     Private WithEvents excelApp As Excel.Application
  13.     Private openExcelInstances As New List(Of Excel.Application)()
  14.  
  15.  
  16.     Private Sub SaveFilePathsToFile()
  17.         Dim filePath As String = Path.Combine(Application.StartupPath, "selected_files.txt")
  18.  
  19.         Using sw As New StreamWriter(filePath)
  20.             For Each item As String In ListBox1.Items
  21.                 Dim filePathForItem As String = savedFilePaths.FirstOrDefault(Function(kvp) kvp.Key = item).Value
  22.  
  23.                 If filePathForItem IsNot Nothing Then
  24.                     Dim line As New StringBuilder()
  25.                     line.Append(item).Append("|").Append(filePathForItem)
  26.                     sw.WriteLine(line.ToString())
  27.                 End If
  28.             Next
  29.         End Using
  30.     End Sub
  31.     Private Function GetFormattedRowData(row As Excel.Range, columnIndices As Dictionary(Of String, Integer), maxColumnWidths As Dictionary(Of String, Integer)) As String
  32.         Dim rowData As String = ""
  33.         For Each header As String In maxColumnWidths.Keys
  34.             If columnIndices.ContainsKey(header) Then
  35.                 Dim cell As Excel.Range = row.Cells(1, columnIndices(header))
  36.                 Dim cellValue As String = If(cell.Value IsNot Nothing, cell.Value.ToString(), "")
  37.                 rowData += cellValue.PadRight(maxColumnWidths(header) + 2)
  38.             End If
  39.         Next
  40.         Return rowData
  41.     End Function
  42.     Private Function PadCellValue(value As String, width As Integer) As String
  43.         Return value.PadRight(width)
  44.     End Function
  45.  
  46.     Private Sub DisplayExcelData(excelData As List(Of List(Of String)), dataGridView As DataGridView)
  47.         dataGridView.Rows.Clear()
  48.         For Each row As List(Of String) In excelData
  49.             If row.Count >= 4 Then
  50.                 dataGridView.Rows.Add(row(0), row(1), row(2), row(3))
  51.             End If
  52.         Next
  53.     End Sub
  54.  
  55.  
  56.     Private Function ReadAndCacheExcelData(filePath As String) As List(Of List(Of String))
  57.         Dim app As Excel.Application = New Excel.Application()
  58.         Dim wb As Excel.Workbook = app.Workbooks.Open(filePath)
  59.         Dim ws As Excel.Worksheet = Nothing
  60.  
  61.         For Each sheet As Excel.Worksheet In wb.Sheets
  62.             If sheet.Name = "Kabelliste" Then
  63.                 ws = sheet
  64.                 Exit For
  65.             End If
  66.         Next
  67.  
  68.         If ws Is Nothing Then
  69.             MessageBox.Show("Sheet 'data' not found in the selected Excel file.")
  70.             Return New List(Of List(Of String))()
  71.         End If
  72.  
  73.         Dim headers As String() = {"K", "C", "A", "D"}
  74.         Dim columnIndices As New Dictionary(Of String, Integer)
  75.  
  76.         For i As Integer = 1 To ws.UsedRange.Columns.Count
  77.             Dim cell As Excel.Range = ws.Cells(1, i)
  78.             Dim header As String = If(cell.Value IsNot Nothing, cell.Value.ToString(), "")
  79.             If headers.Contains(header) Then
  80.                 columnIndices(header) = cell.Column
  81.             End If
  82.         Next
  83.  
  84.         Dim cachedData As New List(Of List(Of String))()
  85.  
  86.         For i As Integer = 2 To ws.UsedRange.Rows.Count
  87.             Dim rowData As New List(Of String)()
  88.             For Each header As String In headers
  89.                 If columnIndices.ContainsKey(header) Then
  90.                     Dim cell As Excel.Range = ws.Cells(i, columnIndices(header))
  91.                     Dim cellValue As String = If(cell.Value IsNot Nothing, cell.Value.ToString(), "")
  92.                     rowData.Add(cellValue)
  93.                 End If
  94.             Next
  95.             cachedData.Add(rowData)
  96.         Next
  97.  
  98.         wb.Close(False)
  99.         app.Quit()
  100.  
  101.         ReleaseObject(ws)
  102.         ReleaseObject(wb)
  103.         ReleaseObject(app)
  104.  
  105.         Return cachedData
  106.     End Function
  107.  
  108.  
  109.  
  110.     Private Sub SaveExcelPaths()
  111.         Dim lines As New List(Of String)
  112.         For Each key As String In fileDict.Keys
  113.             lines.Add($"{key}={fileDict(key)}")
  114.         Next
  115.         File.WriteAllLines("excel.txt", lines)
  116.     End Sub
  117.     Private Sub LoadExcelPaths()
  118.         If Not File.Exists("excel.txt") Then
  119.             Return
  120.         End If
  121.  
  122.         Dim lines As String() = File.ReadAllLines("excel.txt")
  123.         For Each line As String In lines
  124.             Dim parts As String() = line.Split("=")
  125.             If parts.Length = 2 Then
  126.                 fileDict(parts(0)) = parts(1)
  127.             End If
  128.         Next
  129.     End Sub
  130.     Private Sub SaveExcelFilePath(key As String, filePath As String)
  131.         fileDict(key) = filePath
  132.         SaveExcelPaths()
  133.     End Sub
  134.  
  135.     Private selectedItem As String = ""
  136.  
  137.  
  138.     Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
  139.         If ListBox1.SelectedIndex <> -1 Then
  140.             selectedItem = ListBox1.SelectedItem.ToString()
  141.         End If
  142.     End Sub
  143.  
  144.     Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
  145.         If ListBox1.SelectedIndex <> -1 Then
  146.             OpenExcelFileDialog(ListBox1.SelectedItem.ToString())
  147.         End If
  148.     End Sub
  149.  
  150.  
  151.  
  152.  
  153.     Private Sub OpenExcelFileDialog(selectedItem As String)
  154.         Using openFileDialog As New OpenFileDialog()
  155.             openFileDialog.Filter = "Excel Files|*.xlsx;*.xls"
  156.             openFileDialog.Title = "Select an Excel File"
  157.  
  158.             If openFileDialog.ShowDialog() = DialogResult.OK Then
  159.                 Dim filePath As String = openFileDialog.FileName
  160.                 SaveExcelFilePath(selectedItem, filePath)
  161.                 excelDataCache(selectedItem) = ReadAndCacheExcelData(filePath)
  162.                 DisplayExcelData(excelDataCache(selectedItem), DataGridView1)
  163.             End If
  164.         End Using
  165.     End Sub
  166.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  167.         LoadPaths()
  168.         LoadFiles()
  169.         LoadExcelPaths()
  170.         Label1.Text = "Select harness from the list to show KAB."
  171.     End Sub
  172.     Private Sub RadioButton1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton1.Click
  173.         LoadFile("C:\Users\filip\Desktop\Harnesses\c2.txt")
  174.     End Sub
  175.  
  176.     Private Sub RadioButton2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton2.Click
  177.         LoadFile("C:\Users\filip\Desktop\Harnesses\PF.txt")
  178.     End Sub
  179.  
  180.     Private Sub RadioButton3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton3.Click
  181.         LoadFile("C:\Users\filip\Desktop\Harnesses\COMPONENTS.txt")
  182.     End Sub
  183.  
  184.     Private Sub radioButton1_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton1.CheckedChanged
  185.         If RadioButton1.Checked Then
  186.             RadioButton1_Click(sender, e)
  187.         End If
  188.     End Sub
  189.  
  190.     Private Sub radioButton2_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton2.CheckedChanged
  191.         If RadioButton2.Checked Then
  192.             RadioButton2_Click(sender, e)
  193.         End If
  194.     End Sub
  195.  
  196.     Private Sub radioButton3_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles RadioButton3.CheckedChanged
  197.         If RadioButton3.Checked Then
  198.             RadioButton3_Click(sender, e)
  199.         End If
  200.     End Sub
  201.  
  202.     Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
  203.         If e.KeyCode = Keys.Enter Then
  204.             Dim searchText As String = TextBox1.Text.ToLower()
  205.             For i As Integer = 0 To ListBox1.Items.Count - 1
  206.                 Dim currentItem As String = ListBox1.Items(i).ToString().ToLower()
  207.                 If currentItem.Contains(searchText) Then
  208.                     ListBox1.SelectedIndex = i
  209.                     Exit For
  210.                 End If
  211.             Next
  212.         End If
  213.     End Sub
  214.     Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
  215.         If e.KeyCode = Keys.Enter Then
  216.             Dim searchText As String = TextBox2.Text.ToLower()
  217.             For i As Integer = 0 To ListBox2.Items.Count - 1
  218.                 Dim currentItem As String = ListBox2.Items(i).ToString().ToLower()
  219.                 If currentItem.Contains(searchText) Then
  220.                     ListBox2.SelectedIndex = i
  221.                     Exit For
  222.                 End If
  223.             Next
  224.         End If
  225.     End Sub
  226.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
  227.         Dim selectedItem As String = ListBox1.SelectedItem.ToString()
  228.  
  229.         ' Check if folder path is already set
  230.         If folderPaths.ContainsKey(selectedItem) Then
  231.             ' Ask user if they want to change the default folder location
  232.             Dim result As DialogResult = MessageBox.Show($"Are you sure you want to change the default folder location for {selectedItem}?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
  233.  
  234.             If result = DialogResult.Yes Then
  235.                 ' Prompt user to select a new folder location
  236.                 Using folderBrowser As New FolderBrowserDialog()
  237.                     folderBrowser.Description = $"Select a folder for {selectedItem}"
  238.  
  239.                     If folderBrowser.ShowDialog() = DialogResult.OK Then
  240.                         ' Update folder path and save to file
  241.                         folderPaths(selectedItem) = folderBrowser.SelectedPath
  242.                         SavePaths()
  243.                         MessageBox.Show($"Default folder location updated for {selectedItem}")
  244.                     End If
  245.                 End Using
  246.             End If
  247.         Else
  248.             ' If folder path is not set, inform user to double-click on the item
  249.             MessageBox.Show($"Please double-click on {selectedItem} to set the default folder location.")
  250.         End If
  251.     End Sub
  252.  
  253.     Private Sub OpenFolder(ByVal folderPath As String)
  254.         If folderPath <> "" Then
  255.             Try
  256.                 Process.Start("explorer.exe", folderPath)
  257.             Catch ex As Exception
  258.                 MessageBox.Show($"Error opening folder: {ex.Message}")
  259.             End Try
  260.         End If
  261.     End Sub
  262.  
  263.     Private Sub SavePaths()
  264.         Dim lines As New List(Of String)
  265.         For Each key As String In folderPaths.Keys
  266.             lines.Add($"{key}={folderPaths(key)}")
  267.         Next
  268.         File.WriteAllLines("paths.txt", lines)
  269.     End Sub
  270.  
  271.     Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
  272.         Dim selectedItem As String = ListBox1.SelectedItem.ToString()
  273.  
  274.         ' Check if folder path is already set
  275.         If folderPaths.ContainsKey(selectedItem) Then
  276.             ' Open folder in File Explorer
  277.             Try
  278.                 Process.Start("explorer.exe", folderPaths(selectedItem))
  279.             Catch ex As Exception
  280.                 MessageBox.Show($"Error opening folder: {ex.Message}")
  281.             End Try
  282.             Return
  283.         End If
  284.  
  285.         ' If folder path is not set, ask user to select folder
  286.         Using folderBrowser As New FolderBrowserDialog()
  287.             folderBrowser.Description = $"Select a folder for {selectedItem}"
  288.  
  289.             If folderBrowser.ShowDialog() = DialogResult.OK Then
  290.                 ' Set folder path and open folder in File Explorer
  291.                 folderPaths(selectedItem) = folderBrowser.SelectedPath
  292.                 SavePaths()
  293.                 Try
  294.                     Process.Start("explorer.exe", folderBrowser.SelectedPath)
  295.                 Catch ex As Exception
  296.                     MessageBox.Show($"Error opening folder: {ex.Message}")
  297.                 End Try
  298.             End If
  299.         End Using
  300.     End Sub
  301.     Private Function GetSelectedRadioButton() As RadioButton
  302.         If RadioButton1.Checked Then
  303.             Return RadioButton1
  304.         ElseIf RadioButton2.Checked Then
  305.             Return RadioButton2
  306.         ElseIf RadioButton3.Checked Then
  307.             Return RadioButton3
  308.         Else
  309.             Return Nothing
  310.         End If
  311.     End Function
  312.     Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
  313.         Dim selectedRadioButton As RadioButton = GetSelectedRadioButton()
  314.  
  315.         If selectedRadioButton Is Nothing Then
  316.             MessageBox.Show("Please select a radio button")
  317.             Return
  318.         End If
  319.  
  320.         Dim filePath As String = Path.Combine("C:\Users\filip\Desktop\Harnesses", selectedRadioButton.Text & ".txt")
  321.         Dim textToWrite As String = TextBox1.Text & vbCrLf
  322.         File.AppendAllText(filePath, textToWrite)
  323.  
  324.         MessageBox.Show("Harness added to " & selectedRadioButton.Text)
  325.  
  326.         ListBox1.Items.Clear()
  327.         LoadFile(filePath)
  328.     End Sub
  329.  
  330.  
  331.     Private Sub SaveFiles()
  332.         ' Write the contents of the dictionary to the files.txt file
  333.         Dim lines As New List(Of String)()
  334.         For Each kvp As KeyValuePair(Of String, String) In fileDict
  335.             lines.Add(kvp.Key & "," & kvp.Value)
  336.         Next
  337.         File.WriteAllLines("files.txt", lines)
  338.     End Sub
  339.  
  340.     Private Sub LoadFiles()
  341.         ' Check if the files.txt file exists
  342.         If Not File.Exists("files.txt") Then
  343.             Return
  344.         End If
  345.  
  346.         ' Read the contents of the files.txt file and add the entries to the dictionary
  347.         Dim lines As String() = File.ReadAllLines("files.txt")
  348.         For Each line As String In lines
  349.             Dim parts As String() = line.Split(",")
  350.             If parts.Length = 2 Then
  351.                 fileDict(parts(0)) = parts(1)
  352.             End If
  353.         Next
  354.     End Sub
  355.     Private Sub LoadFile(filePath As String)
  356.         If Not File.Exists(filePath) Then
  357.             MessageBox.Show("File not found: " & filePath)
  358.             Return
  359.         End If
  360.         Dim lines As String() = File.ReadAllLines(filePath)
  361.         ListBox1.Items.Clear()
  362.         ListBox1.Items.AddRange(lines)
  363.     End Sub
  364.     Private Sub DisplayExcelData(cachedData As List(Of List(Of String)), dataGrid As DataGridView)
  365.         dataGrid.Rows.Clear()
  366.         For Each rowData As List(Of String) In cachedData
  367.             dataGrid.Rows.Add(rowData.ToArray())
  368.         Next
  369.     End Sub
  370.  
  371.  
  372.  
  373.     Private Sub LoadPaths()
  374.         If File.Exists("paths.txt") Then
  375.             Dim lines() As String = File.ReadAllLines("paths.txt")
  376.             For Each line As String In lines
  377.                 Dim parts() As String = line.Split("=")
  378.                 If parts.Length = 2 Then
  379.                     folderPaths(parts(0)) = parts(1)
  380.                 End If
  381.             Next
  382.         End If
  383.     End Sub
  384.     Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
  385.         ' Get the selected item from ListBox1
  386.         Dim selectedItem As String = ListBox1.SelectedItem.ToString()
  387.  
  388.         ' Check if file location is already set
  389.         If fileDict.ContainsKey(selectedItem) Then
  390.             ' Open file using stored location
  391.             Try
  392.                 Dim startInfo As New ProcessStartInfo()
  393.                 startInfo.FileName = fileDict(selectedItem)
  394.                 startInfo.UseShellExecute = True
  395.                 Process.Start(startInfo)
  396.             Catch ex As Exception
  397.                 MessageBox.Show("Error opening file: " & ex.Message)
  398.             End Try
  399.             Return
  400.         End If
  401.  
  402.         ' If file location is not set, ask user to select file
  403.         Dim selectedFile As String = ""
  404.  
  405.         Using openFileDialog As New OpenFileDialog()
  406.             openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  407.             openFileDialog.Filter = "All Files (*.*)|*.*"
  408.             openFileDialog.FilterIndex = 1
  409.  
  410.             If openFileDialog.ShowDialog() = DialogResult.OK Then
  411.                 selectedFile = openFileDialog.FileName
  412.             End If
  413.         End Using
  414.  
  415.         ' Check if a file was selected
  416.         If String.IsNullOrEmpty(selectedFile) Then
  417.             MessageBox.Show("No file selected.")
  418.             Return
  419.         End If
  420.  
  421.         ' Set file location and save to file
  422.         fileDict(selectedItem) = selectedFile
  423.         SaveFiles()
  424.  
  425.         ' Open the file using the default application
  426.         Try
  427.             Dim startInfo As New ProcessStartInfo()
  428.             startInfo.FileName = selectedFile
  429.             startInfo.UseShellExecute = True
  430.             Process.Start(startInfo)
  431.         Catch ex As Exception
  432.             MessageBox.Show("Error opening file: " & ex.Message)
  433.         End Try
  434.     End Sub
  435.     Private Sub ListBox3_DragEnter(sender As Object, e As DragEventArgs) Handles ListBox3.DragEnter
  436.         If e.Data.GetDataPresent(DataFormats.FileDrop) Then
  437.             e.Effect = DragDropEffects.Copy
  438.         Else
  439.             e.Effect = DragDropEffects.None
  440.         End If
  441.     End Sub
  442.  
  443.     Private Sub ListBox3_DragDrop(sender As Object, e As DragEventArgs) Handles ListBox3.DragDrop
  444.         Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
  445.         For Each file In files
  446.             If Path.GetExtension(file) = ".xls" Or Path.GetExtension(file) = ".xlsx" Then
  447.                 ListBox3.Items.Add(file)
  448.             End If
  449.         Next
  450.     End Sub
  451.  
  452.     Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
  453.         If ListBox3.Items.Count < 1 Then
  454.             MessageBox.Show("Ubaci MACH liste!")
  455.             Return
  456.         End If
  457.         Dim app As Excel.Application = New Excel.Application()
  458.         app.Visible = False ' Make the Excel application visible
  459.  
  460.         Dim wb As Excel.Workbook = app.Workbooks.Add()
  461.         Dim ws As Excel.Worksheet = wb.Worksheets(1)
  462.  
  463.         ' Copy header row
  464.         Dim headerRange As Excel.Range = ws.Range("A1:CD1")
  465.         headerRange.Value = "Header"
  466.  
  467.         Dim rowCount As Integer = 2 ' Start copying data from second row
  468.         Dim headerCopied As Boolean = False
  469.         For Each file As String In ListBox3.Items
  470.             If Path.GetFileName(file) <> "Import-Export.xls" Then
  471.                 If Not headerCopied Then
  472.                     Dim wbHeader As Excel.Workbook = app.Workbooks.Open(file)
  473.                     Dim wsHeader As Excel.Worksheet = wbHeader.Worksheets("Data")
  474.                     Dim headerToCopy As Excel.Range = wsHeader.Range("A1", "CD1")
  475.                     headerToCopy.Copy()
  476.                     headerRange.PasteSpecial(Excel.XlPasteType.xlPasteAll)
  477.                     wbHeader.Close(False)
  478.                     headerCopied = True
  479.                 End If
  480.                 Try
  481.                     Dim wbCopy As Excel.Workbook = app.Workbooks.Open(file)
  482.                     Dim wsCopy As Excel.Worksheet = wbCopy.Worksheets("Data")
  483.                     Dim rangeToCopy As Excel.Range = wsCopy.Range("A2", "CD" & wsCopy.Range("A2").End(Excel.XlDirection.xlDown).Row)
  484.  
  485.                     rangeToCopy.Copy()
  486.                     Dim nextRow As Excel.Range = ws.Range("A" & rowCount)
  487.                     nextRow.PasteSpecial(Excel.XlPasteType.xlPasteAll)
  488.  
  489.                     rowCount += rangeToCopy.Rows.Count
  490.  
  491.                     ' Copy a blank cell
  492.                     wsCopy.Range("A1").Copy()
  493.  
  494.                     wbCopy.Close(False)
  495.  
  496.                     ' Clear the clipboard
  497.                     app.CutCopyMode = False
  498.                 Catch comEx As System.Runtime.InteropServices.COMException
  499.                     MessageBox.Show("An error occurred while processing the file: " & file & vbCrLf & "Error: The 'Data' worksheet was not found in the file.")
  500.                     Return
  501.                 Catch ex As Exception
  502.                     MessageBox.Show("An error occurred while processing the file: " & file & vbCrLf & "Error message: " & ex.Message)
  503.                     Return
  504.                 End Try
  505.             End If
  506.         Next
  507.         Dim columnRange As Excel.Range = ws.UsedRange.Columns
  508.         columnRange.AutoFit()
  509.         app.Visible = True
  510.         openExcelInstances.Add(app)
  511.         ExcelCheckTimer.Enabled = True
  512.         ExcelCheckTimer.Start()
  513.         AddHandler app.WorkbookBeforeClose, AddressOf WorkbookBeforeClose
  514.         excelApp = app
  515.         ' Release objects
  516.         ReleaseObject(ws)
  517.         ReleaseObject(wb)
  518.         ' Do not release the app object here since it will be released in the excelApp_WorkbookBeforeClose method
  519.     End Sub
  520.     Private Sub ExcelCheckTimer_Tick(sender As Object, e As EventArgs) Handles ExcelCheckTimer.Tick
  521.         If excelApp IsNot Nothing AndAlso IsNothing(excelApp.Workbooks) Then
  522.             ExcelCheckTimer.Stop()
  523.             ExcelCheckTimer.Enabled = False
  524.         Else
  525.             Return
  526.         End If
  527.  
  528.         ' If no Excel workbooks are open, quit the Excel application and release its resources
  529.         If excelApp IsNot Nothing Then
  530.             excelApp.Quit()
  531.             Marshal.ReleaseComObject(excelApp)
  532.             excelApp = Nothing
  533.         End If
  534.     End Sub
  535.  
  536.     Private Sub WorkbookBeforeClose(ByVal Wb As Excel.Workbook, ByRef Cancel As Boolean)
  537.         Dim app As Excel.Application = Wb.Application
  538.         Wb.Saved = True ' Mark the workbook as saved to prevent any save prompts
  539.         If app IsNot Nothing Then
  540.             app.Quit()
  541.             Marshal.ReleaseComObject(app)
  542.         End If
  543.     End Sub
  544.  
  545.     Private Sub App_WorkbookBeforeClose(ByVal Wb As Excel.Workbook, ByRef Cancel As Boolean)
  546.         Dim app As Excel.Application = Wb.Application
  547.         If app IsNot Nothing Then
  548.             app.Quit()
  549.             Marshal.ReleaseComObject(app)
  550.         End If
  551.     End Sub
  552.     Private Sub excelApp_WorkbookBeforeClose(ByVal Wb As Excel.Workbook, ByRef Cancel As Boolean) Handles excelApp.WorkbookBeforeClose
  553.         If excelApp IsNot Nothing Then
  554.             excelApp.Quit()
  555.             Marshal.ReleaseComObject(excelApp)
  556.             excelApp = Nothing
  557.         End If
  558.     End Sub
  559.  
  560.     Private Sub ReleaseObject(ByVal obj As Object)
  561.         Try
  562.             System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
  563.         Catch ex As Exception
  564.             Console.WriteLine("Error releasing object: " & ex.Message)
  565.         Finally
  566.             obj = Nothing
  567.             GC.Collect()
  568.         End Try
  569.     End Sub
  570.     Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
  571.         ListBox3.Items.Clear()
  572.     End Sub
  573.  
  574.     Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
  575.         ListBox2.Items.Clear()
  576.         Label1.Text = "Select harness from the list in order to show KAB list."
  577.     End Sub
  578.     Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
  579.         If ListBox1.SelectedIndex <> -1 Then
  580.             Dim selectedItem As String = ListBox1.SelectedItem.ToString()
  581.  
  582.             If fileDict.ContainsKey(selectedItem) Then
  583.                 ListBox3.Items.Add(fileDict(selectedItem))
  584.             Else
  585.                 MessageBox.Show("Selected item does not have a file location.")
  586.             End If
  587.         Else
  588.             MessageBox.Show("Please select an item from the list.")
  589.         End If
  590.     End Sub
  591.  
  592.     Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
  593.         If ListBox1.SelectedIndex <> -1 Then
  594.             Dim selectedItem As String = ListBox1.SelectedItem.ToString()
  595.  
  596.             If fileDict.ContainsKey(selectedItem) Then
  597.                 Dim filePath As String = fileDict(selectedItem)
  598.                 If File.Exists(filePath) Then
  599.                     If Not excelDataCache.ContainsKey(selectedItem) Then
  600.                         excelDataCache(selectedItem) = ReadAndCacheExcelData(filePath)
  601.                     End If
  602.                     DisplayExcelData(excelDataCache(selectedItem), DataGridView1)
  603.                 Else
  604.                     MessageBox.Show("File has been removed or moved! Double-click on the harness to select a new KAB list.")
  605.                 End If
  606.  
  607.                 Label1.Visible = True
  608.                 Label1.Text = $"KAB lista za: {ListBox1.SelectedItem}"
  609.             Else
  610.                 MessageBox.Show("Ovaj harness nema KAB listu! Double-click on the harness to select a KAB list.")
  611.             End If
  612.         Else
  613.             MessageBox.Show("Please select an item from the list.")
  614.         End If
  615.     End Sub
  616.     Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
  617.         If ListBox1.SelectedIndex <> -1 Then
  618.             Dim selectedItem As String = ListBox1.SelectedItem.ToString()
  619.  
  620.             Dim openFileDialog As OpenFileDialog = New OpenFileDialog()
  621.             openFileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm"
  622.             openFileDialog.Title = "Select a KAB List Excel File"
  623.  
  624.             If openFileDialog.ShowDialog() = DialogResult.OK Then
  625.                 Dim newFilePath As String = openFileDialog.FileName
  626.  
  627.                 If fileDict.ContainsKey(selectedItem) Then
  628.                     fileDict(selectedItem) = newFilePath
  629.                 Else
  630.                     fileDict.Add(selectedItem, newFilePath)
  631.                 End If
  632.  
  633.                 MessageBox.Show("Location for " & selectedItem & " changed.")
  634.             End If
  635.         Else
  636.             MessageBox.Show("Please select a harness from the list.")
  637.         End If
  638.     End Sub
  639.  
  640. End Class
  641.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement