Add excel workbook to VB .NET application - excel

I have a project written in Vb .NET in which I take input from the user, open a Excel template and run a macro in it(vba) with input from main form.
I can do all of this without a problem using a path to the template but I need it to be part of the project when I publish it.
This is my path version code(excess code deleted):
Imports Excel = Microsoft.Office.Interop.Excel
private sub OpenExcel()
Dim objApp As Object
Me.Hide()
objApp = CreateObject("Excel.Application")
objApp.WorkBooks.Open("ExampleWorkBook.xlsm")
objApp.visible = True
objApp.Run("MacroName", Var1, Var2)
Me.Close()
End Sub
I have found this post but it doesn't work, maybe because my templates are in a folder(which is located in same location as form1.vb etc).
My templates must be separate from other files so they are easy to find.
If anyone could provide me with a solution/modify code from other post in such a way it works I would be really thankful
I'm using Visual Studio 2017 and Excel 2010
Code from linked post:
Dim filename as String = My.Application.Info.DirectoryPath & System.IO.Path.DirectorySeparatorChar & "WorkbookName.xlsx"
Process.Start(filename)

I have managed to find a solution but then I have run into another problem: I would get an error saying the path is invalid, object is missing. I was sure it was a problem with path but it was related to resource properties(type:content instead of none and copy always so it is in the folder with the application).
Code for opening the excel template:
Imports Excel = Microsoft.Office.Interop.Excel
private sub OpenExcel()
Dim objApp As Object
Me.Hide()
'This path is independent of where the program is installed as it refers to program itself
Dim ResourcePath As String = My.Application.Info.DirectoryPath &
System.IO.Path.DirectorySeparatorChar & "Templates\Rate_Reach_ATT finished.xlsm"
objApp = CreateObject("Excel.Application")
objApp.WorkBooks.Open(ResourcePath)
objApp.visible = True
objApp.Run("MacroName", Var1, Var2)
Me.Close()
End Sub
As for resource itself:
Project>Add existing item>browse>add
Then find the item in solution explorer, open it's properties and change:
Type:Content
Copy to Output Directory: Copy Always
The issue has been fixed so I close this thread

Related

Try to use Microsoft.Office.Interop.Excel with VB.NET in Linux

I would like to use a macro on several excels automatically every day on my linux (debian 9). so I looked for a little bit, and I found that it is possible using VB.NET.
After added microsoft package I installed dotnet-sdk
sudo apt-get install dotnet-sdk-2.1
then create my project with dotnet new console -lang VB
I modified Program.vb to that:
Imports System
Imports System.Text
Imports System.IO
Imports Microsoft.VisualBasic.ControlChars
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop
Module Program
Sub Main(args As String())
ProcessFiles
End Sub
End Module
Sub ProcessFiles()
Dim Filename, Pathname As String
Dim wb As Excel.Workbook
Pathname = ActiveWorkbook.Path & "/path/xlsx/"
Filename = Dir(Pathname & "*.xlsx")
Do While Filename <> ""
wb = Workbooks.Open(Pathname & Filename)
DoWork( wb )
wb.Close( SaveChanges:=True )
Filename = Dir()
Loop
End Sub
Sub DoWork(wb As Excel.Workbook)
With wb
.Worksheets(1).Range("A1").Select
.Selection.End(xlUp).Select
.Rows("1:1").Select
.Selection.AutoFilter
.ActiveSheet.Range("$A$1:$L$999999").AutoFilter( Field:=1 , Criteria1:="<>*2018*" )
.Range("A2:L999999").Select
.Selection.EntireRow.Delete
.Selection.End(xlUp).Select
.ActiveSheet.Range("$A$1:$L$999999").AutoFilter( Field:=1 )
.Rows("1:1").Select
.Selection.AutoFilter
.Range("A2").Select
End With
End Sub
And now, i'm trying run with dotnet run and I have the error : error BC30002: The type 'Excel.Workbook' is not defined.
I've found a lot of answer that give the good import :
Imports Excel = Microsoft.Office.Interop.Excel
but this is not enough. I also found solutions using Visual Studio, but I do not have it and don't want to ...
Thank's for your help
The Excel Interop layer requires (wait for it . . . ) Excel. 8-)
Unless you have found a copy of Microsoft Office for Linux and all the Magic that implements the COM interface, you're out of luck.
Thank's to Terry Carmen for his answer.
We've found another answer without use VB and Excel macro for our needs.
In the case where we would have been forced to use VB and Excels, we could have done it under macOS.

Export Access database to existing excel doc using VBA

So after searching through numerous other pages im still having difficulty and admittedly its due to self teaching myself VBA, so forgive me :(
I have created a simple Phone call counter Access form with a table. My goal is to press a button and it exports the table to a specified directory to an existing XLSM (the data exported would open a new worksheet with the current date as the worksheet name and then save it.
database location is here:
L:\Reports\TestCalltoolmetric.accdb
existing Excel file is here:
L:\Reports\Callcounterreports\MonthlyCallCounter.xlsm
What i have tried so far...
1.
Dim strTable As String
Dim strWorksheetPath As String
strWorksheetPath = "L:\Reports\Callcounterreports"
strWorksheetPath = strWorksheetPath & Format(Date, "ddmmmyy") & "Callreport.xlsx"
This exports my database to a new file with the name of the file as the date+callreport. It works but i dont know if i can use this command to accomplish my goal above (filename isnt really important but at the end of the month i need to provide call metrics so i need every days export all in one workbook so i can create totals).
2.
I tried using this:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "Table1", "L:\Reports\Callcounterreports\MonthlyCallCounter.xlsm"
But it errors out saying that Access database engine could not find the object 'Table1'
3.
I also found through some furious googling a similar request but it was based off exporting a query...in an less than educated mannor i tried adapting it but never really was able to get it to work..
Dim appXL As Object
Dim wb As Object
Dim wks As Object
Dim xlf As String
Dim rs As DAO.Recordset
xlf = "L:\Reports\Callcounterreports\MonthlyCallCounter.xlsm" 'Full path to Excel file
Set rs = CurrentDb.OpenRecordset("Query1") 'Replace Query1 with real query name
Set appXL = CreateObject("Excel.Application")
Set wb = appXL.Workbooks.Open(xlf)
Set wks = wb.Sheets & Format (Date, "ddmmmyy") ' Sheet name
wb.Save
wb.Close
appXL.Quit
Set wb = Nothing
rs.Close
Set rs = Nothing
I know i am by far not the first person to probably ask about how to do this, but any help would be fantastic!
SO....after futher digging i figured out what i was doing wrong with at least using
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "Table1", "L:\Reports\Callcounterreports\MonthlyCallCounter.xlsm"
I first had to rename the table from "Table1" to another name, which i chose "DataTable".
Second i made a mistake on the filepath portion of the command, the location was a networked location which showed up a drive letter. after putting the full and correct file path the form worked like a charm.
https://msdn.microsoft.com/en-us/vba/access-vba/articles/docmd-transferspreadsheet-method-access
i used this website to verify my commands, which now i feel silly that i hadnt found it before.
Big thank you to #dbmitch i think frustration got the better of me instead of really reading the error info..

How to delete an Excel file from a folder using Visual Basic code?

So I have a program that I am creating using Visual Basic through Visual Studio 2015. Form based...I open Excel files, extract data, re-save new data. But I cannot figure out how to delete Excel files....
Here are some code examples:
(open a blank template):
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open("File location")
(modify an existing excel file's data)
'open the existing excel file
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open("c:\Images\" + qcComboBox.Text + ".xlsx")
So once I am done with the excel file how do I permanently delete it?
Regardless of how you access your Excel document, it's still a document in the file system. Just delete your Excel document like this
System.IO.File.Delete(filename)
If you have tried System.IO.File.Delete without luck, maybe you aren't properly cleaning up the reference to the Excel document when you are done with it (common mistake). It is a COM object, and it is not managed by the CLR, unlike normal managed .NET objects. Here's how you can do that. Make a reference to COM >> Microsoft Excel 15.0 Object Library (or whatever version you have). And use this method.
Dim filename = "C:\Users\Public\Documents\test.xlsx"
Dim oExcel As New Microsoft.Office.Interop.Excel.Application()
' The next line is necessary because you don't want to make a reference
' to an unmanaged object two levels deep from an existing unmanaged object.
' Otherwise you won't be able to clean it up properly
Dim oBooks = oExcel.Workbooks
' don't do it this way, as described above
' Dim oBook = oExcel.Workbooks.Open(filename)
Dim oBook = oBooks.Open(filename)
' close your objects, should be enough in most cases
oBook.Close()
oBooks.Close()
oExcel.Quit()
' should not need this but it's an added layer to ensure the objects aren't referenced to
System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel)
' delete as usual
System.IO.File.Delete(filename)

Can't read MS Project 2013 tasks into Excel 2016 VBA

I'm trying to write an Excel 2016 VBA macro that will read the data from a Microsoft Project 2013 Summary Project (Its a project that contains all my active projects) and summarize the data into a summary sheet in Excel.
Here is the code I have so far:
Sub ExtractFromMsProject(ProjectPath As String)
Dim ProjectApp As MSProject.Application
Dim EachProject As MSProject.Project
Dim ProjectFile As MSProject.Project
Dim SubProjectFile As MSProject.SubProject
Dim SubProjectIndex As Long
On Error Resume Next
Set ProjectApp = GetObject(, "MSProject.Application")
If ProjectApp Is Nothing Then
Set ProjectApp = New MSProject.Application
End If
ProjectApp.DisplayAlerts = False
For Each EachProject In ProjectApp.Projects
If ProjectPath = EachProject.FullPath Then
Set ProjectFile = EachProject
Exit For
End If
Next
If ProjectFile Is Nothing Then
If ProjectApp.FileOpenEx(Name:=ProjectPath, ReadOnly:=True) Then
Set ProjectFile = ProjectApp.ActiveProject
Else
MsgBox "Unable to open the source project file '" & ProjectPath & "'."
Exit Sub
End If
End If
ProjectApp.Visible = True
For Each SubProjectFile In ProjectFile.Subprojects
Next
' For SubProjectIndex = 0 To ProjectFile.Subprojects.Count - 1
' Set SubProject = ProjectFile.Subprojects(SubProjectIndex)
' Next
ProjectApp.FileCloseEx pjDoNotSave
ProjectApp.Quit
End Sub
It works great until I get to:
For SubProjectIndex = 0 To ProjectFile.Subprojects.Count - 1
At that line, I get an error message:
"Automation Error. Library not registered"
I've tried to do some Google searching, but everything I found is for an older version of Office/Project.
Any help would be greatly appreciated.
Subproject has been a type for a while. It is a member of Subprojects. So, you can't iterate through the Subprojects collection with a task object.
I would have expected either a type error or an issue with the object being set to "None". That combined with the error message you are getting is making me think that you may have an older version of the MS Project library referenced by your VBA environment. Under Tools > References what you need is the "Microsoft Project 15.0 Object Library".
One other thing. The tasks in the summary project are the inserted project summary tasks. I have never been able to iterate through all the tasks by trying to iterate through the summary project tasks unless the sub projects are unlinked from their source (LinkedToSource = False). Depending on what you are doing it may be just as efficient to iterate through a File System Object for the folder, open each project, extract your data, next ... To do that you will need to include the Microsoft Scripting Runtime in the references too.
Hope that helps. If this answers the question please flag it as such.

programatically add module to xls 2003 using vbscript

The first part is now working [
I have the following which just seems to hang; the part that adds/deletes the module works when running in VBA
I note that I'm prompted with a dialog saying 'this workbook contains links to other data sources' which I ok to, then it hangs
So I tried setting the second argument to 0 and also tried 2 but still it hangs
(2nd arg is UpdateLinks as can be found here )
]
dim objExcel
dim objWorkbook
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open( "H:\M\X\C.xls", 0 , , ,"PASSWORD!" )
Const modpath = "H:\M\V\"
Const modtest = "TEST.cls"
Const modname = "TEST"
On Error Resume Next
Dim vbcomp
Set vbcomp = ActiveWorkbook.VBProject.VBComponents(modname)
objWorkbook.VBProject.VBComponents.Remove vbcomp
objWorkbook.VBProject.VBComponents.Import modpath & modtest
objWorkbook.Save
objWorkbool.Close
set vbcomp = nothing
set objworkbook = nothing
set objExcel = nothing
edited again 14/04/2009
I have now also allowed the 'tools - macro - security - vbproject access'
The script now finishes, however, when trying to open the xls to see if the changes have been made, I get a message informing me that the sheet is locked by "account used to run script"; open 'read only'/notify
Why isn't it releasing control correctly**?**
First thought: Does your workbook already contain a reference (within VBA) to the "Microsoft Visual Basic for Applications Extensibility" library? You'll need it to be able to talk to the VBProject object. Actually, you probably do have the reference if your code works in VBA.
Second thought: ActiveWorkbook is probably not defined outside of an actual workbook. Try replacing it with your objWorkbook object.
Here's a third thought. Did you try setting the Application's DisplayAlerts property to FALSE before you include the module?
The edited script works.
The problem was caused by the fact that I was supplying the password at the workbook level and not at the VBA project level.
A quick search on the web reveals that it is not possible to do this anyway (sendkeys etc) so after manually removing the password on the project, the problem is solved

Resources