Advertisement
ficho2604

Untitled

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