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
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 new pc does NOT need Vsual Studio installed - visual studio creates a standalone EXE that will run without needing VS
The new PC WILL need to have an appropriate version of the .Net Framework installed. Most Windows 10 PCs will meet this requirement, but users will see a message that tells them to install it if not
The new PC WILL need to have Excel installed. Per my comment, if you dont want this or cannot guarantee it (paying for an office licence just to read an excel file is expensive and unnecessary) you should use the ACE driver or EPPlus to read your excel; neither needs Excel and both are free
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 ...
Related
I have developed application using vb 6.0 that creates excel file to export data. I have installed that application on more than 1000 computers that run windows. It is working fine on many computers. But around one out of 50 users complaints that this export facility doesn't work.
Below is my sample code.
Dim objExcel As Excel.Application
Dim objWorkBook As Excel.Workbook
Dim objWorkSheet As Excel.Worksheet
Dim selectedrange As Excel.Range
Set objExcel = New Excel.Application
Set objWorkBook = objExcel.Workbooks.Add
Set objWorkSheet = objWorkBook.Worksheets(Tag)
Set objWorkSheet = objExcel.ActiveSheet
objWorkSheet.Range("A1", "P" & 1000).Font.Name = "Arial"
objWorkSheet.Range("A1", "P" & 1000).Font.Size = 10
objWorkSheet.Cells(2, 1) = "ABCD"
objExcel.Visible = True
objWorkBook.Close (True)
If exporting to excel using VB6.0 is not working on any pc, it never worked after many try on that pc. I have tried 1) re-installing application, 2)registering msexcel35.dll file in windows/system32 folder and windows/syswow64 folder, etc.
but that never worked for me on such computers.
I want that export facility should run on all windows pcs of my application. pls guide me what to do?
I have some code for exporting subform results to Excel workbook. Code works fine, only one small issue. If I do export, excel file opens If user wants I open. When this Excel file is opened and user wants to do Export again, I receive error 1004.
This error is produced because file is open, and new Excel object want to save a file with same name. What I want is when this happens, just cancel everything and let user know that he must first close this previously created workbook. Here is what I tried:
If Err.Number = 1004 Then
MsgBox "Error. You have opened Excel file, that has same name as this file name should be. Please close that file first !", vbCritical
Cancel = True
Set wb = Nothing ' wb is wb=XcelFile.Workbooks.Add
Set XcelFile = Nothing ' Xcelfile is Xcelfile= New Excel.Application
End If
This code works, when user closes that file, export can be performed - old file is just overwritted. Problem is that Excel application is still opened in Windows Task Manager, so Excel object is not properly closed.
Does anybody have a better solution ?
P.S.: I tried including numbers in file name of Excel, so that It wouldn't be same name, but I can't get It fixed.
EDIT: Here is how I tried changing filename
Dim i as Integer
ExcelFilename = "RESULTS_" & Format(Date, "dd/mm/yyyy") & "_" & i & "_" & ".xlsx"
i = i + 1
"i" doesn't change It's value when I run code once again. How can I make it increment ? This would solve my problem...
I suggest a simple solution: add the time to the file name to prevent conflicts.
ExcelFilename = "RESULTS_" & Format(Now(), "yyyy-mm-dd_hh-nn-ss") & ".xlsx"
For a number that will increment as long as the application is running, try
Static i As Integer
Static variables
You must be very strict in opening the Excel objects and closing them in reverse order - as done in this example:
Public Sub RenameWorkSheet()
Dim xls As Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set xls = New Excel.Application
Set wkb = xls.Workbooks.Open("c:\test\workbook1.xlsx")
Set wks = wkb.Worksheets(1)
wks.Name = "My New Name"
wkb.Close True
Set wks = Nothing
Set wkb = Nothing
xls.Quit
Set xls = Nothing
End Sub
I've already read in the forums but noone has my exactly problem, so here we go.
I have my excel and powerpoint files in a OneDrive folder (the Powerpoint is in subfolder), the powerpoint has 100 links.
So, in a forum someone suggested that to get the local OneDrive path, you should turn off the process. I did it.
I have to have the excel file open, because the processing time is really slow if the excel is closed. So If I have opened the excel file and run the macro (in other folder diferent to OneDrive) it runs ok, but if I try to do the same but in the OneDrive folder, it generated the next error into the code line pptShape.LinkFormat.Update:
Error -2147188160 (80048240) in runtime. LinkFormat (unknown member):
Invalid request. The linked file was unavailable and could not be
updated
If I have the excel file closed, the macro runs ok, but the process is so slow (almost 30 minuts), because it open and close the excel a hundred times.
does anyone knows why it happened? How can I fix it? I'll appreaciate your help. here is the code to update the links
Sub updatelinks_1()
Call Shell("cmd.exe /S /C" & "%LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe /shutdown")
Application.DisplayAlerts = ppAlertsNone
Dim pptPresentation As Presentation
Dim pptSlide As Slide
Dim pptShape As Shape
'Set the variable to the PowerPoint Presentation
Set pptPresentation = ActivePresentation
'Loop through each slide in the presentation
For Each pptSlide In pptPresentation.Slides
'Loop through each shape in each slide
For Each pptShape In pptSlide.Shapes
'Find out if the shape is a linked object or a linked picture
If pptShape.Type = msoLinkedOLEObject Then
Dim name, path1, path2, source, begin, search1, cells As String
Dim limit1 As Integer
name = pptShape.LinkFormat.SourceFullName
limit1 = InStr(1, name, "!")
cells = Right(name, Len(name) - limit1)
search1 = "subfoldername"
path1 = Application.ActivePresentation.FullName
begin = InStr(1, path1, search1)
begin = Left(path1, begin - 1)
file1 = Dir(begin & "*.xlsm")
source = begin & file1
End If
path2 = source & "!" & cells
pptShape.LinkFormat.SourceFullName = path2
'update method. code line where generate error
pptShape.LinkFormat.Update
End If
Next
Next
'Update the links (If I use this method on OneDrive folder, it doesn't work and broke all the links because replace the Link name with only the excel file name, not the sheets and cells)
' pptPresentation.UpdateLinks
Call Shell("cmd.exe /S /C" & "start %LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe /background")
Set pptPresentation = Nothing
Set pptSlide = Nothing
Set pptShape = Nothing
Application.DisplayAlerts = ppAlertsAll
End Sub
Good morning everyone.
As I have not seen the solution, I'd like to add my 2 cents.
I have had a similar issue, on a win10 Platform running Office 365.
In my case both files are on the same laptop.
I have seen that the powerpoint VBA procedure to update the path takes a long time by default. ( around 4 Minutes for me as there are 22 linked Objects).
One can speed it up by manually open the target excel file before launching the Powerpoint VBA.
It becomes effectively faster but I hit the issue where for each link the ppt vba procedure tries to update, we get a pop up window telling us that Excel can't open 2 files with same name.
I've tried to add in the PowerPoint VBA procedure : Application.DisplayAlerts = False , but is logically inefficient as applies to the PPT application and not to the Excel app !
I finally found one quick (and logic) solution :
at the beginning of the PowerPoint VBA, I ask user to locate the target excel file :
Set XlApp = CreateObject("Excel.Application")
ExcelFile = XlApp.GetOpenFilename(, , "Would you please locate your excel File")
And after, I just Open the target file, and set it with displayLAerts to False.
XlApp.Visible = True
Set xlWorkbook = XlApp.Workbooks.Open(ExcelFile, True, False)
Doing so, I no longer get warnings.
Full source code available .
Wish you a nice day !
So, a programmer of ours as left the nest and we moved to a Win2012 solution. The website runs fine, everything is good except for excel and in particular just one line of code fails.
We're running ASP classic for the website in IIS, Excel object gets created fine, the chart saves in the correct folder, but when it hits:
wb.SaveAs "D:\WEBSITES\test.xls"
the page conks out with a 500 error then leaves excel in memory in the task manager.
If I remove the save on the XLS, the JPG saves from the chart fine and the code continues and closes down excel properly. Since the code hasnt changed between a 2003 server and this 2012 server Im a bit perplexed as why it decides to fail now.
Any help with this would be most appreciated, I dont know do web stuff and when I do, its normally to sort out COM issues and since it runs, its just a major p.i.t.a. that this bit does not work. Thanks in advance ! :)
<%
Dim xlapp ' Our Excel App
Dim wb ' Our Workbook within the Excel App
Dim ws ' Our Worksheet within the Workbook
Dim crt ' The chart object
Dim SourceRange ' The Source Range for the chart object
Const xlWorkSheet = -4167
Const xlLineMarkers = 65
Set xlapp = CreateObject("Excel.Application")
Set wb = xlapp.Workbooks.Add(xlWorksheet)
Set ws = wb.Worksheets(1)
xlapp.DisplayAlerts = false
Set SourceRange = ws.Range("A3:B6")
Set crt = ws.ChartObjects.Add(0, 0, 480, 383)
crt.Chart.ChartWizard SourceRange, 3, , 2, 1, 0, 2, "Virgin Chaser Report " & formatdatetime(now(),2)
crt.Chart.ChartType = 51
crt.Chart.HasTitle = True
crt.Chart.ChartTitle.Text = "Virgin Chaser Report " & formatdatetime(now(),2)
crt.Chart.ChartTitle.AutoScaleFont = false
crt.Chart.ChartTitle.font.Name = "Arial"
crt.Chart.ChartTitle.font.Size = 12
crt.Chart.ChartTitle.font.Strikethrough = False
crt.Chart.ChartTitle.font.Superscript = False
crt.Chart.ChartTitle.font.Subscript = False
crt.Chart.ChartTitle.font.OutlineFont = False
crt.Chart.ChartTitle.font.Shadow = False
crt.Chart.Export "D:\WEBSITES\test.jpg"
wb.SaveAs "D:\WEBSITES\test.xls"
wb.Saved = True
Set crt = Nothing
Set wb = Nothing
xlapp.Quit
Set xlapp = Nothing
response.end()
%>
Found it: (someone else's fix on stack overflow - this works with Office 2000 too) on Win2012, IIS 8.5
Finally got it fixed. Here was what worked, in case anyone in the future has this same error.
We added BOTH folders:
C:\Windows\System32\config\systemprofile\Desktop
C:\Windows\SysWOW64\config\systemprofile\Desktop
I have some code for exporting subform results to Excel workbook. Code works fine, only one small issue. If I do export, excel file opens If user wants I open. When this Excel file is opened and user wants to do Export again, I receive error 1004.
This error is produced because file is open, and new Excel object want to save a file with same name. What I want is when this happens, just cancel everything and let user know that he must first close this previously created workbook. Here is what I tried:
If Err.Number = 1004 Then
MsgBox "Error. You have opened Excel file, that has same name as this file name should be. Please close that file first !", vbCritical
Cancel = True
Set wb = Nothing ' wb is wb=XcelFile.Workbooks.Add
Set XcelFile = Nothing ' Xcelfile is Xcelfile= New Excel.Application
End If
This code works, when user closes that file, export can be performed - old file is just overwritted. Problem is that Excel application is still opened in Windows Task Manager, so Excel object is not properly closed.
Does anybody have a better solution ?
P.S.: I tried including numbers in file name of Excel, so that It wouldn't be same name, but I can't get It fixed.
EDIT: Here is how I tried changing filename
Dim i as Integer
ExcelFilename = "RESULTS_" & Format(Date, "dd/mm/yyyy") & "_" & i & "_" & ".xlsx"
i = i + 1
"i" doesn't change It's value when I run code once again. How can I make it increment ? This would solve my problem...
I suggest a simple solution: add the time to the file name to prevent conflicts.
ExcelFilename = "RESULTS_" & Format(Now(), "yyyy-mm-dd_hh-nn-ss") & ".xlsx"
For a number that will increment as long as the application is running, try
Static i As Integer
Static variables
You must be very strict in opening the Excel objects and closing them in reverse order - as done in this example:
Public Sub RenameWorkSheet()
Dim xls As Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set xls = New Excel.Application
Set wkb = xls.Workbooks.Open("c:\test\workbook1.xlsx")
Set wks = wkb.Worksheets(1)
wks.Name = "My New Name"
wkb.Close True
Set wks = Nothing
Set wkb = Nothing
xls.Quit
Set xls = Nothing
End Sub