I want to modify an existing Excel file.
The following piece of code generates a duplicate modified excel file in documents folder instead of modifying the original file.
Note: the file which I want to modify is not in the Documents folder
Imports Microsoft.Office.Interop.Excel
Public Class Form1
Public ExcelFolder As String
Public selectedfile As String
Public excel As Application
Public workbook As Workbook
Public sheet As Worksheet
Public r As Range
Public array(,) As Object
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ExcelFolder = "D:\monica\YUKEN\MARK\Excel"
Dim dir As New IO.DirectoryInfo(ExcelFolder)
Dim dir1 As IO.FileInfo() = dir.GetFiles
Dim file As IO.FileInfo
For Each file In dir1
ComboBox1.Items.Add(file)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
selectedfile = ComboBox1.GetItemText(ComboBox1.SelectedItem)
TextBox1.Text = selectedfile
Dim path As String
path = ExcelFolder & "\" & selectedfile
excel = New Application
excel.Workbooks.Open(path)
workbook = excel.ActiveWorkbook
sheet = workbook.Worksheets(1)
r = sheet.UsedRange
' Load all cells into 2d array.
Array = r.Value(XlRangeValueDataType.xlRangeValueDefault)
' Get bounds of the array.
Dim bound0 As Integer = array.GetUpperBound(0) 'last row number
Dim bound1 As Integer = array.GetUpperBound(1) 'last column number
'get total number of rows
Dim totalrows As Integer = bound0 - 1 'since 1st row is header
TextBox2.Text = CStr(totalrows)
sheet.Cells(2, 12) = "YES"
workbook.Save()
workbook.Close()
excel.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel) : excel = Nothing
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook) : workbook = Nothing
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet) : sheet = Nothing
End Sub
End Class