Você está na página 1de 55

Adding Data in Spread COM

a solution for COM developers

2006 FarPoint Technologies, Inc. www.fpoint.com

Contents

CONTENTS
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Deciding How to Add Data to Spread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Bringing in Data Automatically by Binding to a Database . . . . . . . . . . . . . . 7 Add Data Using Code in an Unbound Control . . . . . . . . . . . . . . . . . . . . . . . 17 Loading an Existing File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Data Formatting Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Acronyms Defined . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 About FarPoint.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

2001-2006 FarPoint Technologies, Inc.

Adding Data in Spread COM

Introduction

INTRODUCTION
FarPoint Spread is a powerful spreadsheet/grid control from FarPoint Technologies. This tutorial describes the various ways to add data to a Spread control. You might want to read this tutorial if you want to understand more about Spreads features for adding data. Throughout the tutorial, we assume that you are familiar with the Microsoft Visual Basic development environment and with basic Spread features, such as adding the control to your toolbox, putting the control on a form, and working with cell types. We also assume that you have installed the Spread ActiveX control. If you are using another development environment or control, the concepts presented in the tutorial may still be useful to you. This tutorial is based on the features provided in Spread COM for versions 3.5 and higher. However, much of the information is correct for earlier versions of Spread. This tutorial uses the following icons to highlight certain types of information:
Icon
Tip

Type of Information
Useful information that more advanced users can use right away, but beginners can feel free to skip for now. A step-by-step example to try. To do the examples, have Visual Basic 6 open on your desktop and the Spread ActiveX control installed on your system. Something you might think to do, but is not possible.

Your Turn

Do Not

Be Aware

Information that can be important to know for future reference, but is not needed to do the examples. General conceptual information, mostly for beginners, that helps put the examples in context. The information is general to programming, not to Spread specifically. Pointer to more information or a suggestion of an activity for further learning.

Basics

Do More

This tutorial uses a symbol ( ) to indicate code continued from one line to the next in the paper that should be typed all on one line in the code window.

2001-2006 FarPoint Technologies, Inc.

Adding Data in Spread COM

Overview

OVERVIEW
The Spread control offers several ways to add data to Spread: Binding to a database and bringing in its records automatically Adding data in code Loading an existing file FIGURE 1.

Ways of adding data to Spread

Database

Other file A B 1 2

Spread control Code

fpSpread1.Row = 2 fpSpread1.Col = 2 fpSpread1.Value = 123

This tutorial describes these different ways of adding data to Spread and also provides: Guidelines for deciding when to use the different ways of adding data Information about data validation An introduction to data formatting
Tip

Structure of the Tutorial. This tutorial guides you through the process of deciding how you want to add your data to Spread. It then steps you through the procedures appropriate for your situation. The tutorial begins with the following section. If you want to go directly to a section of interest, see the table of contents on page 2 or the summary of topics in Summary on page 53.

2001-2006 FarPoint Technologies, Inc.

Adding Data in Spread COM

Deciding How to Add Data to Spread

DECIDING HOW
In This Section:

TO

ADD DATA

TO

SPREAD

You learn some of the factors influencing how you add data to Spread. You begin deciding how to add data by determining the source of your data.

Influencing Factors
Many factors can influence how you choose to add data to Spread. Factors include: The form of the data to add. For example, your data may be formatted or unformatted. The destination cell type. Different cell types format data in different ways. The number of rows and columns. Consider using virtual mode for large datasets. For more information about virtual mode, see the Spread Users Guide or the white paper Using Virtual Mode in Spread, available on the FarPoint web site (http://www.fpoint.com/support/whitep/whitep.html). How fast you want the data to load. For example, data binding can be slower than just clipping records in. How you want to access the data after its loaded. For example, if you need to be able to find records in the spreadsheet or persist the changes made to the data, then binding could be the best solution. The Recordset object supports methods for finding particular records, and Spread will write back changes made automatically (unless you override it). Your development environment. Some environments, such as HTML and Visual C++ 1.5, do not offer a data control. The tables in this tutorial help you sort through many of these factors.

2001-2006 FarPoint Technologies, Inc.

Adding Data in Spread COM

Deciding How to Add Data to Spread

Determining the Source of Your Data


Use the following table to help you decide how to best add data to Spread, based on the source of the data. TABLE 1. Start Here to Add Data to Spread
Where is your data?
In a database In code, such as string values or an array. Is your data formatted or unformatted? (To help you decide, see What is Formatted and Unformatted Data? on page 39.)

Then, do this
Bind the database to the Spread control. If your data is formatted, add the formatted data. If your data is unformatted, add the unformatted data.

See these instructions


Bringing in Data Automatically by Binding to a Database Adding Formatted Data on page 18 Adding Unformatted Data on page 25

In an existing file, such as a Spread file, an Excel file, or a tab-delimited file

Load the existing file.

Loading an Existing File on page 32

2001-2006 FarPoint Technologies, Inc.

Adding Data in Spread COM

Bringing in Data Automatically by Binding to a Database

BRINGING IN DATA AUTOMATICALLY TO A DATABASE


In This Section:

BY

BINDING

You understand how simple it is to bind to a database with Spread, a data-aware control. You learn what data-aware controls are. You read an overview of the steps for binding to a database. You step through an example of binding the Spread control to a database.

Introduction to Binding with Spread


In Spreads simplest form, you can view and edit any database supported by Visual Basic by following these simple steps: 1. Attach the Visual Basic Data control to the database. 2. Connect the Spread control to the Data control. 3. Run your application! Spread, being a data-aware control, makes it very easy to bind to a database to bring in data automatically.

What are Data-Aware (Bound) Controls?


Basics

Some type of database is at the core of many, if not most, modern software applications. Before data-aware controls, developers manipulated databases using extensive coding to extract the data from the database and then populate the fields of a form. Extensive coding was also required to allow the user to browse the data, capture the users changes to the data, and then write the changes back to the database. The concept of data-aware, or bound, controls eliminated much of this tedious coding. Now, developers can simply bind a field on a form to a Data control and specify a database table to use. For example, a text box that displays an employees last name might be bound to the LastName field in the Employee table. The Data control handles the tasks of receiving and saving the data, and the control automatically performs navigation functions such as letting the user step back and forth through the database records. A data-aware control is a control that can work with a Data control to display and manipulate data from a database.

2001-2006 FarPoint Technologies, Inc.

Adding Data in Spread COM

Bringing in Data Automatically by Binding to a Database

The first Data control was available in Visual Basic 3.0, and several of the standard Visual Basic controls were modified to be data-aware. Data controls have eliminated so much of the required coding that it is possible to bind to a database in Visual Basic using no code whatsoever. To do anything more complex than simply displaying selected fields from a database, however, requires additional programming. The Spread product provides two versions of the Spread control: one that binds using Data Access Objects (DAO) and one that uses OLE Data Binding (OLE DB), also known as ActiveX Data Objects (ADO). For this tutorial, you will work with the version of the control that uses ADO. Connecting a Data control to a database is as simple as creating a connection string. Connecting a data-aware control to the Data control is also simple: specify the Data control and (for some situations) specify the particular field in the database table to use. The following figure shows these relationships. FIGURE 2.

Relationship between the database, the Data control properties, and the Spread control properties

ADO Data control Biblio.mdb Authors Titles Connection string

DataSource DataField

Database with two tables

Spread control

Tip

Prototype Your Projects. You can use the Data control to prototype your projects. During your design process, you can quickly create sample databases and forms that will allow your users or testers to manipulate actual data and give you feedback on how well your interface works. Hide the Data Control. You can hide the Data control by setting its Visible property to False. By doing so, you can benefit from having your controls easily bound to the Data control, but still be able to create your own code and controls for navigating the database.

Tip

2001-2006 FarPoint Technologies, Inc.

Adding Data in Spread COM

Bringing in Data Automatically by Binding to a Database

Overview of Binding Steps


Here is the big picture of binding: You want to display data from a database in a Spread control on your form. To do this, you put a Data control on your form and specify the database and the table within the database to link to. Then you put a Spread control on your form and connect it to the Data control. To get fancy, you can then customize the Spread control to look and act even more like a sophisticated application.

2001-2006 FarPoint Technologies, Inc.

Adding Data in Spread COM

Bringing in Data Automatically by Binding to a Database

Your Turn

These steps are a brief overview of binding using a Data control and a Spread control. If youre handy with this kind of thing already, you can follow these brief steps and skip the steps in Detailed Steps for Binding on page 10. If youre still learning, these steps give you a preview of the next, more detailed, section. 1. Choose the database to bind to. Either create a new database, or know the name and path of the one you want to use. 2. Create a new Visual Basic project, or open the form to which you want to add the data capability. 3. Place the Visual Basic ADO Data control on the form. Create the connection string for the database with which you want to work. 4. Place the Spread control on the form. In the Spread controls properties, set the DataSource property to specify the Data control to use (specify the Data control you created in Step 3). 5. Customize the Spread control, as described in the Spread Users Guide. For example, you can show certain fields and customize the appearance of the headers.

Detailed Steps for Binding


Your Turn

This section lists the detailed steps for binding a Spread control to a database using ADO with no coding. The major headings in this section match the overview steps in the previous section.

Step One: Choose a database


First, you need a database to which to bind the Data control. For this example, were using biblio.mdb, a sample database that comes with Visual Basic. Make sure a copy of biblio.mdb resides on your hard disk. If it does not, install it from your Visual Basic installation CD.

Step Two: Create the project


Next, you need a program that will display the records in your database. Start a new Visual Basic project.

2001-2006 FarPoint Technologies, Inc.

10

Adding Data in Spread COM

Bringing in Data Automatically by Binding to a Database

Step Three: Add the Data control


Now, you need to add the ADO Data control to your project. The ADO Data control is your projects link to your database. 1. Place the Microsoft ADO Data Control 6.0 (OLEDB) on the form. The icon for the control looks like this in the toolbox:

If the control is not in your toolbox, right-click on the toolbox and choose Components from the pop-up menu. In the Components dialog on the Controls tab, scroll down to find Microsoft ADO Data Control (OLEDB). Select that controls check box, then click OK to add the icon to your toolbox. 2. Leave the Data controls name as the default Adodc1.

3. Right-click on the data control, and then select ADODC Properties from the popup menu. The Property Pages appear.

4. In the Property Pages, on the General property page, under Source of Connection, a. Click the Use Connection String option button.

2001-2006 FarPoint Technologies, Inc.

11

Adding Data in Spread COM

Bringing in Data Automatically by Binding to a Database

b. Click the Build button. The Data Link Properties dialog appears.

5. In the Data Link Properties dialog, on the Provider tab, a. Select Microsoft Jet 3.51 OLE DB Provider (or your preferred provider) from the list of available providers. b. Click the Next button. The Connection tab appears.

2001-2006 FarPoint Technologies, Inc.

12

Adding Data in Spread COM

Bringing in Data Automatically by Binding to a Database

6. On the Connection tab, a. Under item 1 on the tab, provide the database name to connect to either by typing it in the field or by clicking the ellipses button and selecting the database using the Select Access Database dialog. b. Under item 2 on the tab, if necessary, enter the user information required to log on to the database. If you are using the biblio.mdb file, you do not need to enter any user information to log on. c. Click the Test Connection button. d. If the connection succeeded, select OK in the message box. If the connection did not succeed, repeat step 6. 7. In the Data Link Properties dialog, click OK to continue. The Data Link Properties dialog closes, redisplaying the Property Pages. In the Property Pages, your connection string has been created in the Use Connection String text box. 8. In the Property Pages, click the RecordSource property page.

a. On the RecordSource property page, under RecordSource, from the CommandType drop-down list box, select 2 - adCmdTable. b. From the Table or Stored Procedure Name drop-down list box, select the Authors database table if you are using the biblio.mdb database. c. Click the OK button.

Step Four: Add the Spread control


Finally, you need to add the Spread control and link it to the Data control. 1. Add the Spread ADO (OLEDB) components to your project. 2. Place a Spread ADO control on the form. The Spread ADO controls icon looks like this:

2001-2006 FarPoint Technologies, Inc.

13

Adding Data in Spread COM

Bringing in Data Automatically by Binding to a Database

3. In the Spread controls properties, specify the Data control to use. Set the DataSource property of the Spread control to Adodc1.

Since we want to see all the fields in the table (the default choice in Spread), we wont set the DataField property. 4. Size the Spread control and the Data control so you can see more cells. 5. Run the program. Your results should be similar to the following illustration. The Spread control retrieves the database information from the Data control, and then configures itself to display the information from the database. By default, Spread displays all the field values available in the database table. Notice that field names are used as the default column headings, and that each record of the database is a row in the Spread control. The width of the columns depends on the data in the fields. Notice that the first record you see is the first record in the database. By default, Spread sets its cell types to match the databases field types (for example, if the database field is a date, Spread sets the cell type to a date cell). 6. Use the navigation buttons on the Data control to step back and forth through the data displayed in the Spread control.

2001-2006 FarPoint Technologies, Inc.

14

Adding Data in Spread COM

Bringing in Data Automatically by Binding to a Database

Step Five: Customize the Spread control


You can customize how the data is displayed, such as showing only selected fields from the database (with the DataField property), changing the order of the columns, customizing the headers, sizing the columns, and assigning specific cell types. You can also customize how the Spread control interacts with the Data control, such as whether the Data control and the database synchronize the active record and whether user changes will automatically update the database.
Tip

More to ADO. There are other ways you can set up ADO data binding besides the instructions here. For more details on binding using OLE DB and ADO, refer to the Spread Users Guide section on binding to databases, as well as to the white paper ADO and FarPoint Technologies Products available on the FarPoint web site (http://www.fpoint.com/support/whitep/whitep.html). Customize Database Binding. For more information about all these ways of customizing the database binding, refer to the Spread Users Guide. Try Other Databases. Experiment with binding to other databases. Just make sure the database supports access by Visual Basic. Choose one of these options: Create a sample database. You can use a database tool such as Access or Visual Basics Visual DataManager to create a database. Try creating a small database of two fields, containing some of your familys names and birthdays. Name the two fields Name and Birthday. Save the table as FamilyDates in a database file called family.mdb. (Or, create a totally different database that appeals to you.) Use an existing database. Pick a database youve previously created, or use another one that comes with Visual Basic. Or, copy one of your companys databases (one they wont mind you playing with).

Do More

Be Aware

Set the DatabaseName Path. Dont worry about it for this example, but in an actual application you may need to be careful how you specify the path for your database. The path you designate may not match the path used by other machines running your application. You can develop code for determining the actual location of the database at run time.

2001-2006 FarPoint Technologies, Inc.

15

Adding Data in Spread COM

Bringing in Data Automatically by Binding to a Database

Learn More About Binding


Tip

Use the Validate Event. When a user clicks on the navigation buttons on the Data control, the Visual Basic Validate event occurs before the next record is loaded. You can use the Validate event as an opportunity to check that any data a user enters is valid before saving it to the database. Read More. When you are ready, you can also learn more about this topic:
To read more about
Providing data in the best way for use in Spread, with examples for each cell type

Do More

Go to
How Do I Prepare Data to be Added? on page 40

2001-2006 FarPoint Technologies, Inc.

16

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

ADD DATA USING CODE


In This Section:

IN AN

UNBOUND CONTROL

You decide which Spread properties and functions to use when adding formatted data. You decide which Spread properties to use when adding unformatted data. You step through some examples of adding data using Spread properties and functions.

You can use code to add formatted or unformatted data to Spread. You can add data to individual cells or to blocks of cells. The data you add in code can come from several sources, such as a value entered by a user or a value you supply based on the state of the application. This section describes the properties and functions available for adding formatted and unformatted data to Spread at run time, provides some tips on their responsiveness, and gives examples of their use.
To add
Formatted data Unformatted data

Go to
Adding Formatted Data Adding Unformatted Data on page 25

Do More

Read More. When you are ready, you can also learn more about these topics:
To read more about
Formatted versus unformatted data Providing data in the best way for use in Spread, with examples for each cell type

Go to
What is Formatted and Unformatted Data? on page 39 How Do I Prepare Data to be Added? on page 40

2001-2006 FarPoint Technologies, Inc.

17

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

Adding Formatted Data


Adding formatted data means that you are adding the datas formatting along with the data itself. Formatting includes characteristics such as currency symbols and separator characters. The symbols $ and / are examples of formatting. TABLE 2. Decide What Type of Formatted Data You Want to Add
What kind of formatted data do you want to add?
String values (Examples: This is text. or John Doe)

Then do this
Decide how much string data you have to add, as follows: I have a lot of different string values to add. I just need to add string data to one or a few cells.

Use these instructions

Use the Clip property (page 20). For one or two cells, use the Text property (page 18). For more cells, consider using the faster SetText method (page 23).

I need to add the same string value to a row, column, block of cells, or the entire spreadsheet. Some other type of value You will need to declare an array as the type needed to contain the data you want to add.

Use the Text property (page 18). For faster performance, consider using the SetText method (page 23). Use the SetArray method (page 22).

Tip

Response Times. When you use the Text property, you will need to set the Col and Row properties for each cell receiving data. The SetText method provides a faster response time because it combines three calls (setting the row, column, and data) into one. The Clip property is even faster because you can bring in large sets of data at one time and then clip them into selected blocks of cells.

Text Property
Use the Text property to add the same formatted string value to a single cell, a column, a row, a block of cells, or the entire spreadsheet. To use the Text property, first set the Col and Row properties to the cell or cells you want to add data to, and then set the Text property to add the data.
Be Aware

Response Time. The Text property can be slower than the other properties because you need to set the Col and Row properties for each cell or group of cells in which you want to place text. The following steps set up a new project and show how the Text property loads a single cell with data and a row with the same data.

Your Turn

2001-2006 FarPoint Technologies, Inc.

18

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

Set Up a New Project

1. Start a new Visual Basic project. 2. Add a Spread control, and size the control to see several rows and columns. 3. Add a Command button to the form and change its Caption property to Add Data.
Load a Single Cell with Data

4. To add data to any single cell, just specify its row and column coordinates in the Row and Col properties, and then set the Text property to the data. To the buttons Click event, add the following code:
Private Sub Command1_Click() fpSpread1.Row = 1 fpSpread1.Col = 1 fpSpread1.Text = "OneCell" End Sub

5. Run the project, and click the button to see the single cell load with the data. The first cell should have the text OneCell in it. 6. Change the code and run the project several times for other cells and other data.

Do More

Try Other Cell Types. Spreads default cell type is the edit cell. Try adding data to different cell types. For example, use the following code to specify the first cell to be a check box cell that is checked when you run the project:
Private Sub Command1_Click() fpSpread1.Row = 1 fpSpread1.Col = 1 fpSpread1.CellType = CellTypeCheckBox fpSpread1.Text = "1" End Sub

A Text property set to 0 will uncheck the box. Try that. Then try some formatted data for other cell types, as listed in Table 5, Prepare Data for Spread Cell Types, on page 41.

2001-2006 FarPoint Technologies, Inc.

19

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

Load a Row with the Same Data

7. To add the same data to each cell in any single row, just specify the row number in the Row property, set the Col property to 1 to specify all columns, and then set the Text property to the data. In the buttons Click event, change the code to the following:
Private Sub Command1_Click() fpSpread1.Row = 1 fpSpread1.Col = -1 fpSpread1.Text = "Row" End Sub

8. Run the project, and click the button to see the first row load with the data. All the cells in the first row should contain the text Row. 9. Try changing the code and running the project several times for other rows. Try a row of check boxes, too.

Do More

Try Columns. Loading a column with the same data is similar: just specify the column number in the Col property, set the Row property to 1 to specify all rows, and then set the Text property to the data. Try a few columns. Then try adding formatted data to the entire spreadsheet by setting both Row and Col properties to 1. You can also load data into particular headers by setting the Row or Col property, or both, to 0. Try some of those. How Spread Sets Rows and Columns. If you set properties for an entire column or row, Spread stores these properties in a default cell associated with that column or row. This cell does not display on the spreadsheet; it exists only in memory. Each cell in the column or row (except the header cell) inherits the default cells stored properties, unless you override settings for a particular cell. Because the properties are stored in one place, using the default cell takes up less memory and less time to execute than storing property values for individual cells. Note that you must set up header cells separately from their rows or columns.

Tip

Clip Property
Use the Clip property to add different string values into a column, a row, or a block of cells at one time.

2001-2006 FarPoint Technologies, Inc.

20

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

To use the Clip property, first create a tab-delimited string, which is text with tab characters (ASCII 9) separating columns and carriage return/line feed characters (ASCII 13 or 10) separating rows. Set the Col, Row, Col2, and Row2 properties to the block you want to add data to. Then set the Clip property equal to the string.
Tip

Predefined Constants for Tab and Carriage Return. For Visual Basic 5.0 and later, you can use the predefined constants vbTab instead of Chr$(9) for tabs, and vbCr or vbCrLf instead of Chr$(13) or Chr$(10) for carriage return/line feed characters. Response Time. The Clip property can be the fastest property because you can set text into a range of cells, letting you bring in large sets of data at one time and then put them into selected blocks of cells in your spreadsheet. The following steps create a tab-delimited string of alternating X and O characters and then use the Clip property to put the string into the specified block of cells, creating a Tic Tac Toe gameboard. 1. Start a new Visual Basic project. 2. Add a Spread control, and size the control to see several rows and columns. 3. Add a Command button to the form and change its Caption property to Add Data. 4. To the buttons Click event, add the following code:
Private Sub Command1_Click() ' Define the data to clip into the spreadsheet. Dim game As String game = "X" + vbTab + "O" + vbTab + "O" + vbCr + "O" + vbTab + "X" + vbTab + "O" + vbCr + "O" + vbTab + "O" + vbTab + "X" ' Specify the block of the spreadsheet to add the data to. fpSpread1.Row = 1 fpSpread1.Row2 = 3 fpSpread1.Col = 1 fpSpread1.Col2 = 3 ' Clip the data into the spreadsheet. fpSpread1.Clip = game End Sub

Be Aware

Your Turn

2001-2006 FarPoint Technologies, Inc.

21

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

5. Run the project, and click the button to see the block load with the data. You should see a completed Tic Tac Toe gameboard, with the winning X row on a diagonal.

SetArray Method
Use the SetArray method to add any kind of data values from an array into a column, a row, a block of cells, or the entire spreadsheet. To use the SetArray method, first declare an array as the type needed to contain the data you want to add to the spreadsheet. Then call the SetArray method, passing the column and row values of the cell at which to start adding data. The control adds data into the spreadsheet starting at the specified cell, proceeding left to right and top to bottom.
Your Turn

The following steps create an array of numbers and then load the array into the spreadsheet starting at the cell at Column 1, Row 2. 1. Start a new Visual Basic project. 2. Add a Spread control, and size the control to see several rows and columns. 3. Add a Command button to the form and change its Caption property to Add Data. 4. To the buttons Click event, add the following code:
Private Sub Command1_Click() ' Declare variables. Dim i As Integer Dim ret As Boolean Dim quickarray(10) As String ' Define array to use (list of numbers 1 through 10). For i = 0 To 9 quickarray(i) = i + 1 Next i ' Load array values into spreadsheet. ret = fpSpread1.SetArray(1, 2, quickarray) End Sub

2001-2006 FarPoint Technologies, Inc.

22

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

5. Run the project, and click the button to see the spreadsheet load with the array data. You should see the array of numbers load, starting at Column 1, Row 2.

SetText Method
Use the SetText method to add values into a single cell, a column, a row, or the entire spreadsheet. If you set data in multiple cells, the same data is added to each cell, unless you provide code otherwise. To use the SetText method, declare a variable as type Variant and put your data in the variant. Then call the SetText method, passing the column and row values of the cell you want to put the data into. Because the SetText methods data type for values is Variant, the function can accept unformatted, numeric values as well. For example, it can set an integer in an integer cell if you provide the integer value 1234.
Be Aware

Response Time. The SetText method is faster and more concise than the Text property because it combines three calls (setting the row, column, and text) into one. The following steps put a set of different numbers into specified cells. 1. Start a new Visual Basic project. 2. Add a Spread control, and size the control to see several rows and columns. 3. Add a Command button to the form and change its Caption property to Add Data. 4. Since the default cell type in Spread is the edit cell, you do not need to set a cell type for this example. To the buttons Click event, add the following code:
Private Sub Command1_Click() ' Declare variables. Dim i As Integer Dim mycol As Long Dim myrow As Long Dim mytext(10) As Variant ' Put numbers 1-10 at intersections of rows/cols 1-10.

Your Turn

2001-2006 FarPoint Technologies, Inc.

23

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

For i = 0 To 9 mycol = i + 1 myrow = i + 1 mytext(i) = i + 1 ' Load values into spreadsheet. fpSpread1.SetText mycol, myrow, mytext(i) Next i End Sub

5. Run the project, and click the button to see the spreadsheet load with the data. Starting with the first cell, the numbers 1 through 10 should appear diagonally across the spreadsheet.

Do More

Try Another Angle. Try setting myrow or mycol to 2 to see the data load across one row or column. Use Constants. You can use constants with the SetText function to provide the same data to several cells. For example, put the following code in the buttons Click event:
Private Sub Command1_Click() ' Declare variables. Dim mycol As Long Dim myrow As Long Dim mytext As Variant ' Set values. mycol = 1 myrow = 1 mytext = "Hello" ' Load values into spreadsheet. fpSpread1.SetText mycol, myrow, mytext End Sub

Run the project and click the button to see a spreadsheet full of greetings.

2001-2006 FarPoint Technologies, Inc.

24

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

Adding Unformatted Data


Adding unformatted data means that you are adding only the value of the data itself, and not any formatting that may be associated with the data (such as currency symbols or separator characters). You add unformatted data as numeric or string values. TABLE 3. Decide What Type of Unformatted Data You Have to Add
What type of unformatted data do you have to add?
Integer values for integer cells (Examples: 3, 4, 56) Floating-point values for float cells (Examples: 400.00, 1234.5678) Integer values or floating-point values for any cell String data

Then do this
Use the function designed to accept integer values. Use the function designed to accept float values. Use the function that can accept either integer or float values Decide how much string data you have to add, as follows: I have a lot of different unformatted string values to add. I just need to add unformatted string data to one or a few cells.

Use these instructions


Use the SetInteger function (page 29). Use the SetFloat function (page 28). Use the SetText function (page 23).

Use the ClipValue property (page 27). For one or two cells, use the Value property (page 26). For more cells, consider using the faster ClipValue property (page 27).

I need to add the same unformatted string value to a row, column, block of cells, or the entire spreadsheet.

Use the Value property (page 26). For faster performance, consider using the ClipValue property (page 27).

2001-2006 FarPoint Technologies, Inc.

25

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

Value property
Use the Value property to add the same unformatted string value to a single cell, a column, a row, a block of cells, or the entire spreadsheet. To use the Value property, set the Col and Row properties to the cell or cells you want to add data to, and then set the Value property to add the data.
Be Aware

Response Time. The Value property can be slower than the ClipValue property because you need to set the Col and Row properties for each cell or group of cells in which you want to place data. The following steps set up two cells, one as an edit cell and one as a date cell, and then place the same value in each cell. 1. Start a new Visual Basic project. 2. Add a Spread control, and size the control to see several rows and columns. 3. Add a Command button to the form and change its Caption property to Add Data. 4. To the buttons Click event, add the following code:
Private Sub Command1_Click() ' Define Row1 Col1. fpSpread1.Row = 1 fpSpread1.Col = 1 fpSpread1.Value = "02142000" ' Define Row2 Col1 to be a date cell. fpSpread1.Row = 2 fpSpread1.Col = 1 fpSpread1.CellType = CellTypeDate fpSpread1.TypeDateCentury = True fpSpread1.TypeDateFormat = TypeDateFormatMMDDYY fpSpread1.Value = "02142000" End Sub

Your Turn

5. Run the project, and click the button to see both cells load with the same value, but differ because of their cell types and settings.

2001-2006 FarPoint Technologies, Inc.

26

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

Do More

Try Other Cell Types. Try changing the code and running the project several times for other cell types.

ClipValue property
Use the ClipValue property to add different unformatted string values to a block of cells at one time. To use the ClipValue property, first create a tab-delimited string, which is text with tab characters (ASCII 9) separating columns and carriage return/line feed characters (ASCII 13 or 10) separating rows. Set the Col, Row, Col2, and Row2 properties to the block you want to add data to. Then set the ClipValue property equal to the string.
Tip

Predefined Constants for Tab and Carriage Return. For Visual Basic 5.0 and later, you can use the predefined constants vbTab instead of Chr$(9) for tabs, and vbCr or vbCrLf instead of Chr$(13) or Chr$(10) for carriage return/line feed characters. Response Time. The ClipValue property can be faster than the Value property because you can set text into a range of cells, letting you bring in large sets of data at one time and then clip them into selected blocks of cells in your spreadsheet. The following steps create a tab-delimited string of alternating 1 and 0 values (denoting selected and unselected check box cells) and then use the ClipValue property to put the string into the specified block of cells, creating a Tic Tac Toe gameboard of check box cells. 1. Start a new Visual Basic project. 2. Add a Spread control, and size the control to see several rows and columns. 3. Add a Command button to the form and change its Caption property to Add Data. 4. To the buttons Click event, add the following code:
Private Sub Command1_Click() ' Dimension variables. Dim i As Long Dim j As Long Dim game As String ' Define the data to clip into the spreadsheet. game = "1" + vbTab + "0" + vbTab + "0" + vbCr + "0" + vbTab + "1" + vbTab + "0" + vbCr + "0" + vbTab + "0" + vbTab + "1" ' Set game area to be check box cells. For i = 1 To 3 fpSpread1.Row = i For j = 1 To 3 fpSpread1.Col = j

Be Aware

Your Turn

2001-2006 FarPoint Technologies, Inc.

27

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

fpSpread1.CellType = CellTypeCheckBox Next j Next i ' Specify the block of the spreadsheet to add the data to. fpSpread1.Row = 1 fpSpread1.Row2 = 3 fpSpread1.Col = 1 fpSpread1.Col2 = 3 ' Clip the data into the spreadsheet. fpSpread1.ClipValue = game End Sub

5. Run the project, and click the button to see the block load with the data. You should see the completed Tic Tac Toe gameboard, with the winning checked row on a diagonal.

SetFloat Function
Use the SetFloat function for data added as floating-point values. The SetFloat function is similar to the SetText function, but works with float data types as opposed to variants. Also, the SetFloat function is only available for float cells. You can add data to a single cell, a column, a row, or the entire spreadsheet. To use the SetFloat function, declare a variable as type Double and put your value in the double. Then call the SetFloat function, passing column and row values of the cell you want to put the floating-point data into.
Your Turn

The following steps put a set of different floating-point numbers into specified cells. 1. Start a new Visual Basic project. 2. Add a Spread control, and size the control to see several rows and columns. 3. Add a Command button to the form and change its Caption property to Add Data. 4. To the buttons Click event, add the following code:
Private Sub Command1_Click() ' Declare variables. Dim i As Integer

2001-2006 FarPoint Technologies, Inc.

28

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

Dim mycol As Long Dim myrow As Long Dim myfloats(10) As Double ' Set spreadsheet to contain float cells to 4 decimal places. fpSpread1.Row = -1 fpSpread1.Col = -1 fpSpread1.CellType = CellTypeFloat fpSpread1.TypeFloatDecimalPlaces = 4 ' Put float numbers at intersections of rows/cols 1-10. For i = 0 To 9 mycol = i + 1 myrow = i + 1 myfloats(i) = i + 1.5555 ' Load values into spreadsheet. fpSpread1.SetFloat mycol, myrow, myfloats(i) Next i End Sub

5. Run the project, and click the button to see the spreadsheet load with the data. Starting with the first cell, the numbers 1.5555, 2.5555, 3.5555, and so forth should appear diagonally across the spreadsheet.

Do More

Try Another Angle. Try setting myrow or mycol to 2 to see data load across one row or column. Use Constants. You can use constants to provide the same data to several cells. Try replacing the ForNext loop with constants for the SetFloat function parameters.

SetInteger Function
Use the SetInteger function for data added as integer values. The SetInteger function is similar to the SetText function, but works with long integer data types as opposed to variants. Also, the SetInteger function is only available for integer cells. You can add the data into a single cell, a column, a row, or the entire spreadsheet. To use the SetInteger function, declare a variable as type Long and put your value in the long. Then call the SetInteger function, passing the column and row values of the cell you want to put the integer data into.
2001-2006 FarPoint Technologies, Inc. 29 Adding Data in Spread COM

Add Data Using Code in an Unbound Control

Tip

SetInteger Data Types. The SetInteger function sets an integer value, but you must declare its data type as Long. The following steps put a set of different integers into specified cells. 1. Start a new Visual Basic project. 2. Add a Spread control, and size the control to see several rows and columns. 3. Add a Command button to the form and change its Caption property to Add Data. 4. To the buttons Click event, add the following code:
Private Sub Command1_Click() ' Declare variables. Dim i As Integer Dim mycol As Long Dim myrow As Long Dim myintegers(10) As Long ' Set spreadsheet to contain integer cells. fpSpread1.Row = -1 fpSpread1.Col = -1 fpSpread1.CellType = CellTypeInteger ' Put integers 1-10 at intersections of rows/cols 1-10. For i = 0 To 9 mycol = i + 1 myrow = i + 1 myintegers(i) = i + 1 ' Load values into spreadsheet. fpSpread1.SetInteger mycol, myrow, myintegers(i) Next i End Sub

Your Turn

5. Run the project, and click the button to see the spreadsheet load with the data. Starting with the first cell, the integers 1 through 10 should appear diagonally across the spreadsheet.

2001-2006 FarPoint Technologies, Inc.

30

Adding Data in Spread COM

Add Data Using Code in an Unbound Control

Do More

Try Another Angle. Try setting myrow or mycol to 2 to see the data load across one row or column. Use Constants. You can use constants to provide the same data to several cells. Try replacing the ForNext loop with the constants for the SetInteger function parameters.

2001-2006 FarPoint Technologies, Inc.

31

Adding Data in Spread COM

Loading an Existing File

LOADING

AN

EXISTING FILE

In This Section:
You learn the different types of existing files you can load into Spread. You step through an example of loading each type of file.

You can add data to Spread by loading data from an existing file. The steps for adding the data are different depending on the format of the existing file.
Tip

How to Save Files to Load. Saving a file of data as a binary file (Spread-formatted file or Excel-formatted file) preserves all the data and its formatting. Saving a file of data as a text file (delimited file) preserves the data without its formatting. Refer to the Spread Users Guide for information about saving files that you can load into Spread. Saving and loading files of data can be a preferred method for persisting your data.

TABLE 4. Determine What Type of File You have


What type of file is your existing spreadsheet?
Spread-formatted file Delimited file

Description
Files in a Spread-proprietary format (.SS2 or .SS3 extension) Files with data separated separated by tab characters and carriage return/line feed characters (tab-delimited) Files with data separated by user-specified characters, such as commas

See instructions
Loading a Spread-Formatted File on page 33 Loading a Tab-Delimited File on page 35 Loading a Delimited File on page 34 Loading an Excel-Formatted File on page 36

Excel-formatted file

Files formatted in Microsoft Excel 97 or higher (BIFF8 format) (ActiveX or 32-bit DLL only)

Do More

Read More. When you are ready, you can also learn more about these topics:
To read more about
Providing data in the best way for use in Spread, with examples for each cell type How the Spread control handles importing Excel-formatted files

Go to
How Do I Prepare Data to be Added? on page 40 Excel-Formatted File Import/Export guide (Online PDF file)

2001-2006 FarPoint Technologies, Inc.

32

Adding Data in Spread COM

Loading an Existing File

Loading a Spread-Formatted File


Spread files can contain formatted or unformatted data. Spread files are in a proprietary format that only the Spread control or the Spread Designer can read.
Basics

For conceptual information about formatted and unformatted data, see What is Formatted and Unformatted Data? on page 39. The following steps load a Spread file into a Spread control. 1. Find a Spread (.SSx) file and note its path on your machine, where x is the version number. You can use a file called sampledata.ss2 that comes with Spread. (If you performed the default installation of Spread, the file is located in the C:\Program Files\Spreadxx\Samples\ActiveX\VB\ADO\PrintPreview directory, where xx is the version number.) 2. Create a new Visual Basic project. 3. Add a Spread control, and size the control to see several rows and columns. 4. Add a Command button to the form and change its Caption property to Load a Spread File. 5. Add the following code to the buttons Click event to load the file:
Private Sub Command1_Click() Dim ret As Boolean ret = fpSpread1.LoadFromFile("yourpath\yourfile") End Sub

Your Turn

6. Run the project. Click the button to see the file load into the Spread control. (If the file does not load, doublecheck that you have the correct path for the file you are loading.) If you used the sampledata.ss2 file, your form should look like this.

Tip

Spread File Extensions. Spread can read binary (.SS2, etc.) files that were created using previous versions of Spread. Spread binary files are saved with the latest .SSx extension (if saved from Spread Designer), unless you specify otherwise, where x is the version number.

2001-2006 FarPoint Technologies, Inc.

33

Adding Data in Spread COM

Loading an Existing File

Loading a Delimited File


Delimited files contain data separated by characters specified by an application or the user. Common delimited files include tab-delimited files and comma-delimited files. You can create, open, modify, and save delimited files using any standard text editor. In many commonly used database and spreadsheet applications, you can save the database or spreadsheet as a delimited file, such as a comma-delimited file. Spread can open delimited files, including comma-delimited and tab-delimited files. Spread provides a method specifically for opening tab-delimited files, as described in Loading a Tab-Delimited File on page 35.
Your Turn

The following steps load a delimited file into a Spread control. 1. Find or create a delimited file and note its path on your machine. Also note the column and row delimiters used in the file. 2. Create a new Visual Basic project. 3. Add a Spread control, and size the control to see several rows and columns. 4. Add a Command button to the form and change its Caption property to Load a Delimited File. 5. Add the following code to the buttons Click event to load the file. If you would like to use an existing text file, you can use the file delimiters.txt provided in C:\Program Files\Spreadxx\Samples\Files if you performed a default installation. If you use that file, the cell delimiter is not defined, the column delimiter is a comma (,), and the row delimiter is a linefeed, and the file contains data for the column and row headers:
Private Sub Command1_Click() Dim ret As Boolean ret = fpSpread1.LoadTextFile("yourpath\yourfile", "", ",", Chr(10), LoadTextFileColHeaders Or LoadTextFileRowHeaders, "logfilepath\logfilename") End Sub

2001-2006 FarPoint Technologies, Inc.

34

Adding Data in Spread COM

Loading an Existing File

6. Run the project. Click the button to see the file load into the Spread control. (If the file does not load, double-check that you have the correct path for the file you are loading.)

Loading a Tab-Delimited File


Tab-delimited files are text files that contain data separated by tab characters (ASCII 9) and carriage return/line feed characters (ASCII 13 or 10). You can create, open, modify, and save tab-delimited files using any standard text editor. In many commonly used database and spreadsheet applications, you can save the database or spreadsheet as a tab-delimited file.
Your Turn

The following steps load a tab-delimited file into a Spread control. Find or create a tab-delimited file and note its path on your machine. Create a new Visual Basic project. Add a Spread control, and size the control to see several rows and columns. Add a Command button to the form and change its Caption property to Load a Tab-Delimited File. 5. Add the following code to the buttons Click event to load the file: 1. 2. 3. 4.
Private Sub Command1_Click() Dim ret As Boolean ret = fpSpread1.LoadTabFile("yourpath\yourfile") End Sub

2001-2006 FarPoint Technologies, Inc.

35

Adding Data in Spread COM

Loading an Existing File

6. Run the project. Click the button to see the file load into the Spread control. (If the file does not load, double-check that you have the correct path for the file you are loading.)

Loading an Excel-Formatted File


If you are using the Spread ActiveX or 32-bit DLL control, you can load a spreadsheet that is in Excel 97, Excel 2000, or Excel 2002 (BIFF8 format).
Tip

Put Excel in the Middle. The spreadsheet does not have to originate in Excel. You can create it in another application and then export it to the Excel 97, Excel 2000, or Excel 2002 format, usually with an .XLS or .WBK extension. You cannot import an Excel-formatted file that is password-protected. You cannot import files formatted with a version other than Excel 97, Excel 2000, or Excel 2002. Spread Support of Excel. Spread supports many, but not all, of the features in Excel 97, Excel 2000, and Excel 2002 files. The documentation provides a detailed guide summarizing how Spread handles the importing of Excel 97 files. Check the online PDF guide for details about what happens to Excels settings for the spreadsheet, columns and rows, cells, cell types, formulas, formula operations, and other Excel features such as hypertext links, graphs and charts, and merged cells. Spread can issue a log file after each import, listing how Spread handled Excel features for the imported file. Excel features that are new in Excel 2000 and Excel 2002 are not listed in the appendix and are not supported by Spread. The following steps load an Excel-formatted file into a Spread control. 1. Find or create an Excel-formatted file and note its path on your machine. You can use a file called Book1.xls that comes with the Spread Ex-Con (Excel Conversion) sample. (If you performed the default installation of Spread, the file is located in the C:\Program Files\Spreadxx\Samples\ActiveX\VB\ADO\ExcelIO directory.) 2. Create a new Visual Basic project. 3. Add a Spread control, and size the control to see several rows and columns. 4. Add a Command button to the form and change its Caption property to Load an Excel File.

Do Not

Be Aware

Your Turn

2001-2006 FarPoint Technologies, Inc.

36

Adding Data in Spread COM

Loading an Existing File

5. In this step, you add code to check that the file is in Excel format, determine how many sheets are in the Excel workbook, and then load the first sheet. Add the following code to the buttons Click event:
Private Sub Command1_Click() ' Declare variables. Dim x As Integer Dim y As Boolean Dim z As Boolean Dim Var As Variant Dim sheetcount As Integer Dim handle As Integer ' Dimension the SheetList array to allow for redimensioning. Dim SheetList() As String ' Verify that the target file is an Excel-formatted file. x = fpSpread1.IsExcelFile("yourpath\yourfile") ' If the file is an Excel file... If x = 1 Then ' Get the SheetList to determine how many sheets exist. y = fpSpread1.GetExcelSheetList("yourpath\yourfile", Null, sheetcount, "", handle, True) ' ReDim the SheetList array to the exact number of sheets. ReDim SheetList(sheetcount) ' Get the SheetList again to retrieve entire list of sheets. y = fpSpread1.GetExcelSheetList("yourpath\yourfile", SheetList, sheetcount, "", handle, False) ' Note that the last parameter is False this time, to prevent ' the SheetList from being loaded into memory again. ' If getting the SheetList is successful... If y = True Then ' Import the first sheet (index 0) of the Excel file. z = fpSpread1.ImportExcelSheet(handle, 0) End If End If End Sub

2001-2006 FarPoint Technologies, Inc.

37

Adding Data in Spread COM

Loading an Existing File

6. Run the project. Click the button to see the file load into the Spread control. (If the file does not load, double-check that you have the correct path for the file you are loading.)

Tip

All Workbook Sizes. This code works for all sizes of Excel workbooks. If you know how many sheets are present, or can dimension the SheetList array to a sufficiently large value, you can avoid the code for calling the initial GetExcelSheetList method and for redimensioning the SheetList array.

2001-2006 FarPoint Technologies, Inc.

38

Adding Data in Spread COM

Data Formatting Concepts

DATA FORMATTING CONCEPTS


In This Section:
You learn the difference between formatted and unformatted data. You understand how Spread validates data. You learn how to prepare formatted and unformatted data in a form ready to be added to Spread.

What is Formatted and Unformatted Data?


Basics

Data can be either unformatted or formatted: Unformatted data is just the data itself. Formatted data includes the data, along with characteristics that identify the data. For example, the numeric value 5000 is just plain, unformatted data. But $5,000 is formatted data. The currency symbol ($) and separator character (,) are formatting characters that identify the numeric value as money (in the United States anyway).

Tip

Meanings of Format. The word format has slightly different meanings. Formatting characteristics identify data. An example is the currency symbol ($50.00 is formatted data). Format can also refer to the order of the data or the rules a data string must follow. An example is the time cell. When you supply unformatted (characteristic-less) data to a time cell, you need to supply it in a format (order) that the cell recognizes, specifically HHMMSS. Keep this subtle difference in meaning in mind as you read this tutorial.

Does Spread Validate the Entered Data?


Spread performs some data validation on data entered into cells: Some cell types provide properties that let you control the range of values allowed. For example, the float cell offers the TypeFloatMin and TypeFloatMax properties for setting the minimum and maximum float values allowed in the cell. Some cell types provide properties that let you specify the format the entered data must follow. For example, the date cell offers the TypeDateFormat and other properties that let you specify whether the style of the date is MM/DD/ YY or some other style.

2001-2006 FarPoint Technologies, Inc.

39

Adding Data in Spread COM

Data Formatting Concepts

When a cell validates its data and finds invalid data, the EditError event occurs and the supplied data is not displayed. The event provides several error codes that indicate the type of validation error.
Tip

You can provide your own code in events such as the EditError or Change events to validate the entered data. Refer to the Spread ActiveX Reference Guide for more information about the events and about about how each cell type validates data.

How Do I Prepare Data to be Added?


The examples in this section use the Text and Value properties to demonstrate how you can prepare and add formatted and unformatted data to Spread. Spread offers several properties and functions for using code to add data to a spreadsheet: If you want to add formatted data, you can use the Text property. You can also use other properties and functions listed in Adding Formatted Data on page 18. If you want to add unformatted data, you can use the Value property. You can also use another property listed in Adding Unformatted Data on page 25.

Learn about Spread Cell Types


Spread is a powerful grid component, with many different types of cells available for you to customize. Each cell type has its own set of useful and flexible characteristics. As a result, each type of cell accepts formatted and unformatted data in its own unique way: Some cell types require very different forms of formatted and unformatted data. For example, to provide formatted data for a combo box cell type, you can provide the cells list items in a formatted data string (First Item and Second Item). To provide unformatted data, however, you provide a value indicating an items index in the item list. Other cell types require formatted data in the exact manner specified by the cells formatting properties, which you can set. For example, a time cell that you set to display time in the format HH:MM:SS p.m. would expect formatted data such as 12:15:20 p.m. It would not accept 12:15:20 and would display nothing in a cell given the invalid value. Some cell types require unformatted data in a certain format. Unformatted time cell data, for example, must be supplied in the format HHMMSS. A time cell would not accept 1215 as a valid unformatted value. Other cell types are more flexible in the data they accept. The float cell type, for example, can always accept data with no formatting. The PIC cell type attempts to fit whatever data it receives into its specified mask format.

2001-2006 FarPoint Technologies, Inc.

40

Adding Data in Spread COM

Data Formatting Concepts

Some cell types accept the same data for both formatted and unformatted forms. Integer cells accept only integers with no formatting.

Summary of Cell Types and Data


The following table summarizes the formatted and unformatted forms of data for each cell type. It also provides tips on how the cell type works or how you can use the cell type. For more information about each cell type, refer to the Spread Users Guide. The examples that follow the table let you experiment with using the Text and Value properties to provide formatted and unformatted data for all the cell types. TABLE 5. Prepare Data for Spread Cell Types
For Spread Cell Type
Button

Prepare formatted data in this form


0 for the up state 1 for the down state Null for the not set state (looks up, but has not been changed) 0 for the unchecked state 1 for the checked state 2 for the indeterminate state Null for the not set state (looks unchecked, but has not been changed) Data string to indicate selected list item. Example: text = "Item One" selects Item One from the example list in the Tips column. Data string in the format expected by the cells property settings. Example: "06/06/2001" Data string. Example: "This is an edit cell."

Prepare unformatted data in this form


0 for the up state 1 for the down state

Tips
Set the TypeButtonType property to Two-State to maintain a pressed button in its down state. Set the TypeCheckType property to Three-State to include an indeterminate state.

Check Box

0 for the unchecked state 1 for the checked state 2 for the indeterminate state

Combo Box

Index value (base zero) to indicate selected list item. Example: value = 1 selects Item Two from the example list in the Tips column. Use format MMDDYYYY. Example: 06062001

Add listed data to cell using the TypeComboBoxList property, and use tabs between list items. Example: "Item One" + Chr$(9) + "Item Two" Date cells display imported data according to the cells TypeDateFormat property and other property settings. To provide multiple lines, set the TypeEditMultiLine property to True. Then use ASCII 10 characters where the lines should break. Use the MaxTextCellHeight property to adjust cell height. Use the TypeMaxEditLen property to set the maximum number of characters.

Date

Edit

Data string. Example: "This is an edit cell."

2001-2006 FarPoint Technologies, Inc.

41

Adding Data in Spread COM

Data Formatting Concepts

TABLE 5. Prepare Data for Spread Cell Types (Continued)


For Spread Cell Type
Float

Prepare formatted data in this form


Formatted data string, or value with no formatting characters. Examples: "$2,124.63" 100.1234 No formatting characters. Example: 123456 Not applicable.

Prepare unformatted data in this form


Remove any currency or separator characters. Examples: 2124.63 100.1234 No formatting characters. Example: 123456 Not applicable.

Tips
Float cells display imported data according to the cells TypeFloatSeparator property and other property settings.

Integer

Owner-Drawn

Use the TypeOwnerDrawStyle property and DrawItem event to define your own style for the cell. Use the TypePicMask property to define the cells mask.

PIC

Data string in the format expected by the cells mask, including non-mask characters. Example: "(999)123-4567" Not applicable.

Supply only the data. Remove all nonmask characters. Example: 9991234567 Not applicable.

Picture

Add picture data to cell using the TypePictPicture property. To provide multiple lines, set the TypeTextWordWrap property to True. Then use ASCII 10 characters where the lines should break. Use the MaxTextCellHeight property to adjust cell height. Use the TypeMaxEditLen property to set the maximum number of characters. Time cells display imported data according to the cells TypeTime24Hour property and other property settings.

Static Text

Data string. Example: "This is static text."

Data string. Example: "This is static text."

Time

Data string in the format expected by the cells property settings. Use a space between the time value and an indicator. Example: "02:14:27 p.m."

Use format HHMMSS, with HH in 24-hour format. Example: 141427

Your Turn

The following example creates a small spreadsheet that shows each of the twelve Spread cell types, and then lets you experiment with providing different formatted and unformatted data for each cell type. You can do some or all of the Optional steps, depending on which cell types you need to provide data for.

2001-2006 FarPoint Technologies, Inc.

42

Adding Data in Spread COM

Data Formatting Concepts

Step One: Start the project


1. Start a new Visual Basic project. 2. Add a Spread control, and size the control to see several rows and columns. 3. Add a Command button below the spreadsheet.

Step Two: Define the spreadsheet size and the cell type labels
1. To the projects Form_Load() event, add the following code:
Private Sub Form_Load() ' Label controls Command1.Caption = "Add data to cell types" Form1.Caption = "Data in Spread cell types" ' Dimension size of spreadsheet fpSpread1.MaxRows = 12 fpSpread1.MaxCols = 2 ' Set width of columns fpSpread1.ColWidth(1) = 10 fpSpread1.ColWidth(2) = 15 ' Remove scroll bars and size sheet automatically fpSpread1.ScrollBars = ScrollBarsNone fpSpread1.AutoSize = True ' Set up column headers fpSpread1.Row = 0 fpSpread1.Col = 1 fpSpread1.Text = "Cell Type" fpSpread1.Col = 2 fpSpread1.Text = "Formatting Example" ' Set up cell type labels in Column 1 ' Define labels Dim labels As String labels = "Button" + vbCr + "Check Box" + vbCr + "Combo Box" + vbCr + "Date" + vbCr + "Edit" + vbCr + "Float" + vbCr + "Integer" + vbCr + "Owner Drawn" + vbCr + "PIC" + vbCr + "Picture" + vbCr + "Static Text" + vbCr + "Time" ' Define target area to load labels into fpSpread1.Row = 1 fpSpread1.Row2 = 12 fpSpread1.Col = 1 fpSpread1.Col2 = 1 ' Load labels into target fpSpread1.Clip = labels End Sub

2001-2006 FarPoint Technologies, Inc.

43

Adding Data in Spread COM

Data Formatting Concepts

2. Run the project. Your project should look similar to the illustration at right. 3. If necessary, adjust your project to look like the illustration. For example, you will need to have the extra spacing between the spreadsheet rows and the command button to allow for the cell type examples to expand the heights of some of the cells in the spreadsheet. 4. In the Click event for the command button, prepare Column 2 for more code by adding the following code to your project:
Private Sub Command1_Click() fpSpread1.Col = 2 End Sub

5. Decide which of the following twelve optional steps you want to complete (which cell types are you interested in adding data to?). You can do some or all of the optional steps. If you do each optional step, your project will create an example of each of the twelve Spread cell types and will look similar to the illustration at right.

Optional Step: Button Example


1. To the buttons Click event, add the following code to the existing code to create an example for the button cell type:
fpSpread1.Row = 1 fpSpread1.RowHeight(1) = 15 fpSpread1.CellType = CellTypeButton fpSpread1.TypeButtonType = TypeButtonTypeTwoState
2001-2006 FarPoint Technologies, Inc. 44 Adding Data in Spread COM

Data Formatting Concepts

fpSpread1.TypeButtonShadowSize = 4 fpSpread1.TypeButtonText = "Press this button" fpSpread1.Text = 0

2. Run the project and click the Add data to cell types button to view the button example. You used the Text property to set the button in an up state. 3. Edit the code to change the Text propertys value from 0 to 1. 4. Run the project and click the Add data to cell types button to see the difference in button style (the button is now pressed, or down). 5. Edit the code to change the last line of the button example code to
vaSpread1.Value = 0

6. Run the project and click the Add data to cell types button. You used the Value property to set the button in an up state. Try a Value of 1 also, to set the button to its down state. As illustrated by this example, the Text and Value properties for button cells accept the same data (for details, see Table 5 on page 41). Note that the Text property supports an additional value, setting the control to Null to indicate that the user has not interacted with the control.

Optional Step: Check Box Example


1. To the buttons Click event, add the following code to create an example for the check box cell type:
fpSpread1.Row = 2 fpSpread1.CellType = CellTypeCheckBox fpSpread1.TypeCheckType = TypeCheckTypeThreeState fpSpread1.TypeCheckText = "Check this box" fpSpread1.Text = 0

2. Run the project and click the Add data to cell types button to view the check box example. You used the Text property to set the cell to its unchecked state. 3. Edit the code to change the Text propertys value from 0 to 1. 4. Run the project and click the Add data to cell types button to see the difference in check box style (the box is now checked). Try the same for a value of 2 (making the box indeterminate). 5. Edit the code to change the last line of the check box example code to
vaSpread1.Value = 0

6. Run the project and click the Add data to cell types button. You used the Value property to set the cell to its unchecked state. Try the values of 1 and 2 also.

2001-2006 FarPoint Technologies, Inc.

45

Adding Data in Spread COM

Data Formatting Concepts

As illustrated by this example, the Text and Value properties for check box cells accept the same data (for details, see Table 5 on page 41). Note that the Text property supports an additional value, setting the control to Null to indicate that the user has not interacted with the control.

Optional Step: Combo Box Example


1. To the buttons Click event, add the following code to create an example for the combo box cell type:
fpSpread1.Row = 3 fpSpread1.CellType = CellTypeComboBox fpSpread1.TypeComboBoxList = "Choose an item" + vbTab + "Item One" + vbTab + "Item Two" fpSpread1.Text = "Choose an item"

2. Run the project and click the Add data to cell types button to view the combo box example. You used the Text property to indicate the selected list item in the cell by naming the item. 3. Edit the code to change the Text propertys value to Item One. 4. Run the project and click the Add data to cell types button to see that Item One is now the selected combo box entry. Try the same for the value Item Two. 5. Edit the code to change the last line of the combo box example code to
fpSpread1.Value = 0

6. Run the project and click the Add data to cell types button. You used the Value property to indicate the selected list item in the cell by specifying the items index value. Try the values of 1 and 2 also. As illustrated by this example, for combo box cells, the Text and Value properties require different data input (for details, see Table 5 on page 41).

Optional Step: Date Example


1. To the buttons Click event, add the following code to create an example for the date cell type:
fpSpread1.Row = 4 fpSpread1.CellType = CellTypeDate fpSpread1.TypeDateFormat = TypeDateFormatMMDDYY fpSpread1.TypeDateSeparator = Asc("/") fpSpread1.Text = "10/01/00"

2. Run the project and click the Add data to cell types button to view the date example for October 1, 2000. You used the Text property to provide a formatted date.

2001-2006 FarPoint Technologies, Inc.

46

Adding Data in Spread COM

Data Formatting Concepts

3. Edit the code to change the Text propertys value to 10/01/2000. 4. Run the project and click the Add data to cell types button to see that nothing displays in the cell. The date cell in this example requires the MMDDYY format for successful Text property input. Try the same for other formats you can think of, such as 10.01.00. 5. Edit the code to change the last line of the date example code to
fpSpread1.Value = 10012000

6. Run the project and click the Add data to cell types button to view the formatted date for October 1, 2000. You used the Value property to provide an unformatted date. 7. Try a value of 100100. Run the project and click the Add data to cell types button to see that nothing displays in the cell. The date cell requires Value property data to use the MMDDYYYY format. As illustrated by this example, for date cells, the Text and Value properties require different data input (for details, see Table 5 on page 41).

Optional Step: Edit Example


1. To the buttons Click event, add the following code to create an example for the edit cell type:
fpSpread1.Row = 5 fpSpread1.CellType = CellTypeEdit fpSpread1.Text = "Type some text in this edit cell." ' Adjust for multiple lines of text Dim newheight As Integer fpSpread1.TypeEditMultiLine = True newheight = fpSpread1.MaxTextCellHeight fpSpread1.RowHeight(5) = newheight

2. Run the project and click the Add data to cell types button to view the edit example. You used the Text property to supply a data string. 3. Edit the code to change the Text propertys value to a longer string of words (up to 60 characters) or just a few characters. 4. Run the project and click the Add data to cell types button to see the cell size adjust automatically to the length of your text. 5. Edit the code to change the fpSpread1.Text line of the edit example code to
fpSpread1.Value = "whatever text you want to type here"

6. Run the project and click the Add data to cell types button. You used the Value property to supply a data string.

2001-2006 FarPoint Technologies, Inc.

47

Adding Data in Spread COM

Data Formatting Concepts

As illustrated by this example, the Text and Value properties for edit cells accept the same data (for details, see Table 5 on page 41).
Tip

Change the Number of Characters Allowed. You can use the TypeMaxEditLen property to adjust the maximum allowed number of characters.

Optional Step: Float Example


1. To the buttons Click event, add the following code to create an example for the float cell type:
fpSpread1.Row = 6 fpSpread1.CellType = CellTypeFloat fpSpread1.TypeFloatDecimalPlaces = 2 fpSpread1.TypeFloatMoney = True fpSpread1.TypeFloatSeparator = True fpSpread1.Text = 1234.56

2. Run the project and click the Add data to cell types button to view the float example for $1,234.56. You used the Text property to provide an unformatted value, but the float cells properties supplied the proper formatting. 3. Edit the code to set the TypeFloatMoney and TypeFloatSeparator properties to False. Then run the project and click the Add data to cell types button. Observe that the float cell no longer displays the currency symbol and separating comma. 4. Edit the Text propertys value to
fpSpread1.Text = "$1234.56"

5. Run the project and click the Add data to cell types button. Observe that the float cell disregards the new formatting you provided because the cell is not displaying a currency symbol at this point. 6. Return the TypeFloatMoney and TypeFloatSeparator property settings to True, then run the project and click the Add data to cell types button to see the formatting accepted. 7. Edit the code to change the last line of the float example code to
fpSpread1.Value = 1234.5678

8. Run the project and click the Add data to cell types button to view the float value of $1,234.57 (the specified value rounded to the specified two decimal places and formatted for currency). You used the Value property to supply an unformatted value, and the float cell provided the proper formatting.

2001-2006 FarPoint Technologies, Inc.

48

Adding Data in Spread COM

Data Formatting Concepts

9. Edit the code to set both the TypeFloatMoney and TypeFloatSeparator separator properties to False, then run the project and click the Add data to cell types button to see that the float cell removes the currency formatting. As illustrated by this example, the Text and Value properties do not require strict data input for float cells, because the float cells properties control the display (for details, see Table 5 on page 41).

Optional Step: Integer Example


1. To the buttons Click event, add the following code to create an example for the Integer cell type:
fpSpread1.Row = 7 fpSpread1.CellType = CellTypeInteger fpSpread1.Text = 123456789

2. Run the project and click the Add data to cell types button to view the Integer example. You used the Text property to provide an unformatted integer value. 3. Try adding formatting characters to the Text propertys value, such as
fpSpread1.Text = "123,456,789"

4. Run the project; observe that the integer cell type does not accept formatting characters. 5. Edit the code to change the last line of the integer example code to
fpSpread1.Value = 123456789

6. Run the project and click the Add data to cell types button. You used the Value property to provide an unformatted integer value. As illustrated by this example, the Text and Value properties for integer cells accept the same data (for details, see Table 5 on page 41).

Optional Step: Owner-Drawn Example


1. To the buttons Click event, add the following code to create a blank cell for the owner-drawn cell type:
fpSpread1.Row = 8 fpSpread1.CellType = CellTypeOwnerDrawn

2. The owner-drawn cell does not accept string data. An example of the code showing an owner-drawn cell is beyond the scope of this lesson on formatted and unformatted data. Take a break!

2001-2006 FarPoint Technologies, Inc.

49

Adding Data in Spread COM

Data Formatting Concepts

Do More

Do Your Own Owner-Drawn Example. When Spread displays an ownerdrawn cell, the DrawItem event occurs. You must provide code in this event to draw the cell in the style you want. You define the style as a long integer value in the cells TypeOwnerDrawStyle property. When Spread displays the cell, the value of the TypeOwnerDrawStyle property determines which style included in the DrawItem event to use. You can use Windows API calls to draw figures such as ellipses, circles, and rectangles in an owner-drawn cell. For more information, refer to the Spread Reference Guide and to the demonstration examples provided with Spread.

Optional Step: PIC (Mask) Example


1. To the buttons Click event, add the following code to create an example for the PIC cell type:
fpSpread1.Row = 9 fpSpread1.CellType = CellTypePic fpSpread1.TypePicMask = "(999) 999-9999" fpSpread1.Text = "(123) 456-7890"

2. Run the project and click the Add data to cell types button to view the PIC example of the formatted telephone number. You used the Text property to provide formatted data for the cell. 3. Edit the code to set the Text property to 1234567890. 4. Run the project and click the Add data to cell types button and observe that the cell masking tries to interpret some of the numbers as formatting (parentheses, space, and hyphen). The PIC cell requires formatted data to match its masking. 5. Edit the code to set the Text property to 12345. 6. Run the project and click the Add data to cell types button to observe how the cell masking does not have enough data to complete the intended format. 7. Edit the code to change the last line of the PIC example code to
fpSpread1.Value = 1234567890

8. Run the project and click the Add data to cell types button. You used the Value property to provide an unformatted value, which the cell formatted. As illustrated by this example, for PIC cells, the Text property requires strictly formatted data, while the Value property does not (for details, see Table 5 on page 41).

Adding Data in Spread COM

50

2001-2006 FarPoint Technologies, Inc.

Data Formatting Concepts

Optional Step: Picture Example


1. To the buttons Click event, add the following code to create an example for the picture cell type:
fpSpread1.Row = 10 fpSpread1.CellType = CellTypePicture fpSpread1.TypePictPicture = LoadPicture("C:\Windows\circles.bmp")

2. The picture cell does not accept string data. Take another break! Or, import your favorite picture into the example. Spread installs several pictures you can try. (Use the .BMP files in C:\Program Files\Spreadxx\Samples\Files, if you performed the default installation.)

Optional Step: Static Text Example


1. To the buttons Click event, add the following code to create an example for the static text cell type:
fpSpread1.Row = 11 fpSpread1.CellType = CellTypeStaticText fpSpread1.Text = "This is static text." ' Adjust for multiple lines of text Dim newheight As Integer fpSpread1.TypeTextWordWrap = True newheight = fpSpread1.MaxTextCellHeight fpSpread1.RowHeight(11) = newheight

2. Run the project and click the Add data to cell types button to view the static text example. You used the Text property to provide a data string. 3. Edit the code to change the Text propertys value to a longer string of words (up to 60 characters) or just a few characters. 4. Run the project and click the Add data to cell types button to see the cell size adjust automatically to the length of your text. 5. Edit the code to change the fpSpread1.Text line of the static text example code to
fpSpread1.Value = "whatever text you want to type here"

6. Run the project and click the Add data to cell types button. You used the Value property to provide a data string.

2001-2006 FarPoint Technologies, Inc.

51

Adding Data in Spread COM

Data Formatting Concepts

As illustrated by this example, the Text and Value properties for static text cells accept the same data (for details, see Table 5 on page 41).
Tip

Change the Number of Characters Allowed. You can use the TypeMaxEditLen property to adjust the maximum allowed number of characters.

Optional Step: Time Example


1. To the buttons Click event, add the following code to create an example for the time cell type:
fpSpread1.Row = 12 fpSpread1.CellType = CellTypeTime fpSpread1.TypeTime24Hour = TypeTime24Hour12HourClock fpSpread1.Text = "02:15 pm"

2. Run the project and click the Add data to cell types button to view the time example. You used the Text property to provide a formatted time value. 3. Edit the code to set the Text property to 02:15. 4. Run the project and click the Add data to cell types button. Nothing displays in the cell. The cell requires the exact formatting specified by the TypeTime24Hour property. 5. Try setting the Text property to other formats you can think of, such as 2:15 pm or 14:15, then run the project and click the Add data to cell types button. 6. Edit the code to change the last line of the time example code to
fpSpread1.Value = 141500

7. Run the project and click the Add data to cell types button to see the formatted time. You used the Value property to provide an unformatted time value. 8. Try changing the value to 1415 or other values, and then run the project and click the Add data to cell types button. As illlustrated by this example, for time cells, the Text property requires more strict formatting than the Value property does (for details, see Table 5 on page 41). You have finished the example!

Adding Data in Spread COM

52

2001-2006 FarPoint Technologies, Inc.

Summary

SUMMARY
The following table summarizes the various ways of adding data in Spread and points you to the appropriate page for more detail.
Ways of Adding Data in Spread
Bring in data automatically by binding to a database. Add data in code in an unbound control. Load an existing spreadsheet.

Options
Bind to a database without using any code. Add formatted data in code. Add unformatted data in code. Load from a Spread-formatted file. Load from a tab-delimited file. Load from a delimited file Load from an Excel-formatted file.

Page
7

18 25 33 35 34 36

As you can see, the ways of adding data can include the option of adding formatted or unformatted data, which can affect how you load the data. The following table summarizes the conceptual information in this tutorial and points you to the appropriate section for more detail.
Conceptual Information
What data-aware (bound) controls are The difference between formatted and unformatted data How Spread validates data How to provide data in the best way for adding to Spread, with examples for each cell type

Page
7 39 39 40

2001-2006 FarPoint Technologies, Inc.

53

Adding Data in Spread COM

Acronyms Defined

ACRONYMS DEFINED
This tutorial uses the following acronyms.
Acrony m
ADO BIFF8 CD DLL HTML OCX OLE DB VBX

Definition
ActiveX Data Objects BInary File Format 8 (Excel 97 and Excel 2000 format) Compact Disk Dynamic Link Library HyperText Markup Language 32-bit ActiveX control eXtension Object Linking and Embedding for DataBases 16-bit Visual Basic control extension

Adding Data in Spread COM

54

2001-2006 FarPoint Technologies, Inc.

Adding Data in Spread COM

ABOUT FARPOINT
FarPoint Technologies, Inc., a privately held company with corporate headquarters located in Morrisville, North Carolina, USA, is a leading developer and publisher of professional components for Windows development. Our award-winning tools benefit leading corporations, software companies, and independent consultants around the world as a costeffective solution for building distributed enterprise-wide applications for commercial or inhouse use. From the CEO to our newest team member, our goals are the same: to provide you with the innovative tools and support you need to effectively compete in today's competitive development market. FarPoint's foundation began in 1991 (then Prescription Software) by re-introducing Drovers Professional Toolbox for Windows, what is believed to be the first development package available for the professional Windows developer, with thirteen new DLLs, including a fully featured spreadsheet control. Developers using languages such as C or C++ quickly realized the benefits of using our pre-built DLLs instead of spending their valuable resources to develop these controls internally. The advent of Visual Basic 1.0 presented FarPoint with a new opportunity in the professional development market. After Microsoft asked that our spreadsheet be made available for their users, we introduced the first spreadsheet control ever available for Visual Basic in our product Visual Architect. Along with the spreadsheet control, Visual Architect offered formatted-edit controls in this new VBX format. The rising popularity of Visual Basic and our controls allowed us to introduce several new products to the market in the coming months: Spread/VBX, Aware/VBX, Grid/VBX, Tab/VBX, and Tab Pro, while continuing support for Professional Toolbox for Windows. Today, FarPoint is one of the oldest and most respected vendors in the industry. We continue to cater our products to professional Visual Basic and Visual C++ developers by offering our components as a 32-bit ActiveX control, 16- and 32-bit DLLs, and a VBX control. Our award-winning tools benefit leading corporations, software companies, and independent consultants around the world as a cost-effective solution for building distributed enterprisewide applications for commercial or in-house use. For more information, check out our web site or contact us directly at the North American office or European office of FarPoint:
North America Contact FarPoint Technologies, Inc. 808 Aviation Parkway Suite 1300 Morrisville, NC 27560 USA Phone: 919-460-4551 email: fpsales@fpoint.com Web: www.fpoint.com Europe Contact FarPoint Europe Ltd. Whiteleaf, Roundabout Lane West Chiltington Pulborough, West Sussex RH20 2RL England Tele: +44 (0) 1798 812 372 Fax: +44 (0) 1798 813 049 email: salesEurope@fpoint.com

Information in the white paper is subject to change without notice and does not represent a commitment on the part of FarPoint Technologies, Inc. 2001-2006 FarPoint Technologies, Inc. All rights reserved. Unless otherwise noted, all names of companies, products, street addresses, and persons contained herein are part of a completely fictitious scenario or scenarios and are designed solely to document the use of a FarPoint Technologies, Inc., product. Spread COM is a trademark of FarPoint Technologies, Inc. Other brand and product names are trademarks or registered trademarks of their respective holders.

2001-2006 FarPoint Technologies, Inc.

www.fpoint.com

1-800-645-5913

Você também pode gostar