I have an error while trying to open two excel files with giving only their names and not the full path (error: file not exist), the files are both in the same folder as the project (Debug). I am trying to not use a static path so when i change the laptop the project will always work. This is the code that i am using. Thanks for your help
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
xlApp = New Excel.Application
xlBook = xlApp.Workbooks.Open(Filename:="c:\EMP_.xlsx", IgnoreReadOnlyRecommended:=True, ReadOnly:=False, Editable:=True)
xlSheet = xlBook.Worksheets(1)
If DataGridView1.DataSource IsNot Nothing Then
Dim i, j As Integer
For i = 1 To DataGridView1.RowCount - 1
For j = 1 To DataGridView1.ColumnCount
xlSheet.Cells(i + 1, j) = DataGridView1.Rows(i - 1).Cells(j - 1).Value
Next
Next
xlApp.Visible = True
xlApp.UserControl = True
xlApp.Quit()
xlApp = Nothing
Else
MsgBox("Le tableau est vide")
End If
Use an OpenFileDialog to show a user interface that you can choose which excel file you want to open. They're easy to use:
Dim ofd as New OpenFileDialog
Dim result = ofd.ShowDialog
If result <> DialogResult.OK Then Return 'if the user cancels
xlApp.Workbooks.Open(Filename:= ofd.Filename ...
Per Jimi's comment, something like this will read an xlsx that is alongside the exe:
Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "emp_.xlsx")
Path.Combine(Application.StartupPath, "emp_.xlsx")
Always use Path.Combine to combine paths, not string concatenation
You asked about moving the app to another PC:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.