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