Write programs for control Excel using VB.NET
It used to always write some VBA programs under Excel, and hundreds of lines of code can basically solve problems. Never used VC or VB, Delphi to do this. I think there are more relative scale and functions if I do a statement, which should be the focus of Excel development.
This time I used VB.NET to develop a small program that visited Excel read data and modified, there were some experienced things and everyone shared, if I was wrong, please refer to it.
It is generally divided into such a part to explain:
It is generally divided into such a part to explain:
1. Preparation:
Preparation We need to add Excel Library reference to the project: I use Office2003, its library file is Microsoft Excel 11.0 Object Library. If you use Excel2000, then it is using Microsoft Excel 9.0 Object Library.
When we need it, we add the imports namespace.
I just visited Excel's data in this program, and I don't need to name the space.
2, declare some objects:
These objects do not need, the three should have, behind, what object you need:
DIM EXCELAPP AS EXCEL.Application 'declares an Application object
DIM Excelworkbook as Excel.Workbook 'declares a workbook object
DIM EXCELSHEET AS Excel.Worksheet 'declares a worksheet object
Wait ...
DIM EXCELRANGE AS Excel.Range 'declares a range object
3. Access an Excel file:
Excelapp = New Excel.Application
Excelworkbook = excelapp.workbooks.open (strfile) 'Access to workbook: This strfile is the path to the file, I get from the open file dialog.
Excelsheet = Excelworkbook.sheets.Item (1) 'Access to worksheet: Item uses an index value to get a reference to the Sheet object
Excelsheet.Activate
We can get the values in this file:
Define a String variable:
Dim strCellvalue as string
StrcellValue = Excelsheet.cells (1, 1) .value 'Get the contents of the A1 cell.
When you modify it, it is ok:
Excelsheet.cells (1, 1) .value = strCellvalue
4, after the good:
4, after the good:
Operate the Excel object in each exit port of the program, save or not save:
Excelworkbook.save
Excelworkbook.close
Excelapp = Nothing
5 Others:
5 Others:
Need to note that the above code requires some fault tolerance mechanism, such as:
If NOT EXCELWORKBOOK Is Nothing Then to achieve the correct operation of the program
Need to judge
Excel
There is no open. If there is
Excel
The process is running. Your code is likely to affect the open
Excel
Like
Excelworkbook.close
Although such a statement has a good specified workbook in front, it is not possible to make a reckless operation, we need to judge
Excel
Operation.