Reading and Parsing Excel in .NET - vb.net

I have googled, and rummaged through stackoverflow with no luck on the matter.
I have found countless ways to import an entire excel file into a datagridview, but this is not what I want.
Basically, I have an excel file with multiple users (in one column) and a unique ID in another column. I want to only parse specific users and the corresponding unique ID from that row.
How Can I do this?

There are several ways to read the contents of an Excel file. One possibility is to use Excel's object model through the Excel Interop API. Using this approach, you'll interact with Excel using objects:
Imports Microsoft.Office.Interop
Public Class ExcelReader
Public Sub Read(filename As String)
Dim excel As New Excel.Application
Dim book As Excel.Workbook = excel.Workbooks.Open(filename)
Dim sheet As Excel.Worksheet = book.Worksheets("Sheet1")
Dim first_cell_text As String = sheet.Cells(1, 1).Value().ToString
Dim a_number As Integer = sheet.Cells(1, 2).value
End Sub
End Class
You need to add a reference to the Excel interop DLL, which on my machine is located at C:\Program Files (x86)\Microsoft Visual Studio 9.0\Visual Studio Tools for Office\PIA\Office12\Microsoft.Office.Interop.Excel.dll. I am pretty sure you need to have Excel installed on any machine that runs the app, too.
Documentation for the Excel object model is available here.
Other options include reading an Excel file as if it were a database using ADO.NET, and using third party libraries that can read Excel.

Related

Getting UCase, Trim, Left libary errors in VBA

I have a application that opens excel files. When I run a macro function in my excel that was opened with the application. I'm getting Compile error "Can't find project or library" on the "UCase" "Trim" "Left" just to name a few. In my macro functions, I have multiply cases of using the above functions. I also have references to "Visual Basic For Application", "Microsoft Excel 12.0 Object Library", "OLE Automation", "Microsoft Office 12.0 Library", Microsoft Forms 2.0 Object Library."
If I run excel by itself without the application, there is no errors. Is there any explanation to why this is happening? Libraries mix match? Works fine for the developer and a few but as for the rest of users, they will get these errors.
It's because those methods belong to Excel Application so that you must call them by preceding their name with the Excel object name (and possibly with its relevant member, too) you must have instantiated before
for instance
example 1: late binding
Option Explicit
Sub LateBindingExcel()
Dim xlApp As Object 'declaring your application object as of "Object" type doesn't require any reference to Excel library
' open an Excel session
Set xlApp = CreateObject("Excel.Application")
' call Excel application WorksheetFunction.Trim()
MsgBox xlApp.WorksheetFunction.Trim(" see how spaces get trimmed by this function ")
End Sub
example 2: early binding
Option Explicit
Sub EarlyBindingExcel()
Dim xlApp As Excel.Application 'declaring your application object as of "Excel.Application" type requires adding Excel library reference to your project
' open an Excel session
Set xlApp = CreateObject("Excel.Application")
' call Excel application WorksheetFunction.Trim()
MsgBox xlApp.WorksheetFunction.Trim(" see how spaces get trimmed by this function ")
End Sub
one sensible difference between the two binding "styles" is that the latter allows you exploiting IntelliSense features while the former doesn't
It is likely due to the 'Visual Basic for Applications' in the Tool reference refers to non-presence library. This may happen if the developer use the library in their customized directory instead of default library.
There are 2 means to solve the issue.
Make global replacement of all string related functions (Format, Left, Right, Mid, Trim etc) with prefix VBA. e.g. VBA.Left. This will force the use of functions within standard library.
Move all your excel sheets to another new workbook and then, select the 'Visual Basic for Applications' from Tool reference.

How to access a Word public variable in Excel VBA

I'm trying to automate some report generation where Excel VBA is doing all the work. My employer has a standardized set of templates of which all documents are supposed to be generated from. I need to populate one of these templates from Excel VBA. The Word templates utilize VBA extensively.
This is (some of) my Excel VBA code:
Sub GenerateReport() ' (Tables, InputDataObj)
' code generating the WordApp object (works!)
WordApp.Documents.Add Template:="Brev.dot"
' Getting user information from Utilities.Userinfo macro in Document
Call WordApp.Run("Autoexec") ' generating a public variable
Call WordApp.Run("Utilities.UserInfo")
' more code
End sub
In the Word VBA Autoexec module, a public variable named user is defined and declared. The Userinfo sub from the Utilities module populates user. Both these routines are run without any complaints from VBA. I would then like to be able to access the user variable in my Excel VBA, but I get the following error
Compile Error: Variable not yet created in this context.
How can I access the Word VBA variable in Excel VBA? I thought it more or less was the same?
EDIT: the user variable is a user defined Type with only String attributes. Copying the Word VBA functions that populate the user variable is absolutely doable, just more work than I though was necessary...
In a Word module:
Public Function GetUserVariable() As String '// or whatever data type
GetUserVariable = user
End Function
In an Excel module:
myUser = WordApp.Run("GetUserVariable")
Alternatively, you could be able to replicate the variables value - as it's called user I suspect it is returning some information about a user, or author, of a document. In which case one of the following might be what you're after:
'// Username assigned to the application
MsgBox WordApp.UserName
'// Username defined by the system
MsgBox Environ$("USERNAME")
'// Name of the author of the file specified
MsgBox CreateObject("Shell.Application").Namespace("C:\Users\Documents").GetDetailsOf("MyDocument.doc", 9)
Another option - if you could only add a line of code to the Utilities.UserInfo sub (after setting your public variable):
ActiveDocument.Variables("var_user") = user
Then you could access it easily afterwards in Excel:
Sub GenerateReport() ' (Tables, InputDataObj)
' code generating the WordApp object (works!)
'I am assuming your WordApp object is public, as you don't declare it.
'Capture the new document object
Dim newdoc as Object
set newdoc = WordApp.Documents.Add(Template:="Brev.dot")
' Getting user information from Utilities.Userinfo macro in Document
Call WordApp.Run("Autoexec") ' generating a public variable
Call WordApp.Run("Utilities.UserInfo")
'Get and show the value of "user"
Dim user as String
user = newdoc.Variables("var_user")
msgbox, user
End Sub
This is assuming that useris a string.
EDIT: As it is a requirement to work only on the Excel VBA, I would definely try the approach suggested by Scott and MacroMan - replicating the same functionality of the Word macros in Excel - if possible.
I assume that you've already ruled out the possibility of using an edited copy of the original template, set in a public folder...
For the sake of completness, there is another possibility: actually it is possible to inject VBA code in a Word document without the VBProject Object Model, by "brute force". If you rename a Word document as a .zip file and open it, you will notice a \word\vbaProject.bin file in it. This file contains the VBA project for the document and, in principle, one could add or change VBA code by modifying or replacing it.
I did some tests transplanting code from one document to another by simply copying the vbaProject.bin file, and the concept works. If you are interested in learning more about this file, this topic could be of use.
Notice, however, that to do what you want with such a technique would be somewhat complex (it would involve, for starters, updating zip files from your Excel VBA), and would require a lot of experimentation to mitigate the risk of accidentally corrupting your files. Definetly not recommended if you are looking for an easy and simple solution - but it is possible.

vb.net windows form connection excelworkbook

I'm creating a vb.net excellworkbook.xlsx file and worksheet from windowsform want to achieve. I could not. I do not make a connection between vb.net and windowsform. I need to use in my project, but dozens excelworkbook excelworkbook excel in the program I need to do without opening the windows forms and links to all the relevant supposed to do. I would be glad if you can help.
Frankly, I have almost no clue what you're asking. Almost no clue anyway.
Access, read and write an excel workbook in Visual Studio vb.net by doing the following:
Click Project > Add Reference > COM > Microsoft Excel Object Library
In your code you will need:
Imports Microsoft.Office.Interop
Then you can create the excel object:
Dim ExcelAp As New Excel.Application
Open a workbook:
Dim WrkBk As Excel.Workbook = ExcelAp.Workbooks.Open("Path")
And then access cells and their values:
WrkBk.Cells(1, 1).value = "Hello World!"
That might give you a start anyway.

Why doesn't code work in VB.net, but works in VBA; GetObject

VBA code works great:
Sub testVBA()
Dim wb As Object ' Lotus123.Document
Set wb = GetObject("S:\Temp\T\0375D.WK3", "Lotus123.Workbook")
End Sub
VB.net code fails:
Sub TestVBNet()
Dim wb As Object ' Lotus123.Document
wb = GetObject("S:\Temp\T\0375D.WK3", "Lotus123.Workbook")
End Sub
In VB.net I get a FileNotFoundException: "File name or class name not found during Automation operation."
As I can run it from VBA that means the file exists and that the class name exists. So why doesn't it work and how can I fix it in VB.net.
EDIT: I guess I'm not sure how to start diagnosing this: Obviously the class exists on my computer but somehow VB.net doesn't manage to find it. Maybe VB.net uses a different method to activate the class. Maybe a registry entry is missing. I am glad for any suggestions.
Edit 2: I also tried using CreateObject and got this error: "Cannot create ActiveX component." Not unexpected.
For some reason VB.net cannot find the class name "Lotus123.Workbook" so I tried getting the file without the class name and it works fine in XP.
Dim wb As Object ' Lotus123.Document
wb = GetObject("S:\Temp\T\0375D.WK3")
EDIT: In Win8 64bit the above doesn't work; just hangs.
The code below works in XP 32 bit as well as in Win8 64 bit. I checked with process monitor what is happening under the hood. CreateObject checks for the CLSID in the registry using the given object. Then it looks up the necessary info using the CLSID.
Public Shared Function GetLotusWB(ByVal sFile As String) As Object
'HKCU takes precedence if exists
'HKCU\Software\Classes\Lotus123.Workbook\CLSID
'HKCU\Software\Classes\CLSID\{29130007-2EED-1069-BF5D-00DD011186B7}
'normally this is used because Lotus123 doesn't create HKCU entries
'HKCR\Lotus123.Workbook\CLSID = {29130007-2EED-1069-BF5D-00DD011186B7}
'HKCR\CLSID\{29130007-2EED-1069-BF5D-00DD011186B7}\InprocHandler32 = ole32.dll
'HKCR\CLSID\{29130007-2EED-1069-BF5D-00DD011186B7}\LocalServer32 = C:\Lotus\123\123w.exe
'using object as that sometimes works better
Dim LotusObj As Object = CreateObject("Lotus123.Workbook")
'get application
'need a reference to Lotus 123 else declare as Object
Dim LotusApp As Lotus123.Application = LotusObj.Application
'FAILS: LotusApp.Visible = True
'open file; also works fine As Lotus123.Document
Dim ldoc As Object = LotusApp.OpenDocument(sFile)
'visible and activate (must declare as Object else gives exception)
Dim appObject As Object = ldoc.Application
appObject.Visible = True
ldoc.Activate()
Return ldoc
End Function
This works great because it creates the "Lotus123.Workbook" which is used to get the application object.
Load the file into an Excel workbook. It should be able to convert the lotus123 workbook on the fly.
First of all, check to make sure your inclusions (I think under Tools menu, includes or references or something like that) include the library that references Lotus123.Document. Chances are it's in the "Microsoft Excel 14.0 Object Library" or similar.
I've heard it said that VB is not VBA!

Add a reference to WorkBook in Visual Studio (2012) VB.net Project

I have a solution in VS 2012 called T1. Under it I have several projects, mostly VB. One of those projects is an Excel template (xltx). I've added references to all sorts of other projects in the solution (carefully), but the Excel Project doesn't show up in:
Add Reference ==> Solution ==> Projects
Is there a way to do this? The solution is an Excel Add-in for reference.
In addition to all my other projects (mostly devoted to data transformations), I'm hoping to: open an Excel template, add values and sheets to that template from an Access database (the sheets would ideally come from other templates), save the file with a date name, and email it to a list of email addresses (probably in OutLook).
I am specifically failing here:
Dim objWorkbook As Excel.Workbook = objApp.Workbooks.Open()
I can get that to work with a path to a local file, but I can't seem to figure out how to reference the template I'm including in the solution.
Thanks.
I am not sure how to reference a workBook. But to read Excel file, the best way for me to read/write excel is using NetOffice. You can check the document and tutorial/code for more info. Code example to read a cell is
using Excel = NetOffice.ExcelApi;
public String GetCellValueFromSheetIndexCellID(int sheetIndex = 1, String cellID = "A1")
{
Excel.Application exApp = new Excel.Application();
Excel.Workbook book = exApp.Workbooks.Open(this.path);
Excel.Worksheet sheet = book.Worksheets[sheetIndex] as Excel.Worksheet;
string returnVal = String.Empty;
returnVal = GetRangeValue(sheet.Range(cellID));
exApp.Quit();
exApp.Dispose();
return returnVal;
}
With this library, you can also edit an excel file. Hopefully this helps.
I believe you have to do the following:
Dim objWorkBook = Globals.Thisworkbook
Microsoft choose not to let people know about this.
Or you will need to do the following:
Dim objWorkBook = ExApp.Workbooks.Open("full path to workbook")