C H A P T E R 15 | Microsoft Office 97/Visual Basic Programmer's Guide |
Developing Applications for the Internet and World Wide Web |
The Internet provides an effective solution for broadcasting information across different platforms. For example, many organizations use the Internet to distribute product information, directories, or company policy manuals to people both within and outside of the organization. By applying Internet technologies to their internal network, organizations can help their employees share, analyze, and find information more easily.
Microsoft Office 97 is a flexible and robust tool for creating Internet content. By using the Microsoft Office Internet features, you can create applications to publish and distribute information to peers, management, and other functional groups in a timely manner, regardless of where they are located. For example, you can enter data into a Microsoft Access database, and then publish that database on your company's Web server so that users on a variety of platforms can access that data with a Web browser.
In Microsoft Word, Microsoft Excel, Microsoft PowerPoint, and Microsoft Access, you can use Visual Basic for Applications to automate and extend Internet features in your custom applications.
In all likelihood, you are well aware of what the Internet is, and you've had a chance to take advantage of its many resources. Even if you have used the Internet, the following overview will help to make sure you understand the terms used to describe it in this chapter.
The Internet is a collection of computer networks that connects millions of computers around the world. The World Wide Web is a client/server technology used to access a vast variety of digital information from the Internet. By using a software client called a Web browser, such as Microsoft Internet Explorer, and a modem or other connection to an Internet Service Provider (ISP), you can easily access text, graphics, sound, and other digital information from practically any computer in the world that is running the appropriate server software on the Internet.
Internet Protocols
A Web browser uses a variety of standardized methods for addressing
and communicating with Internet servers. These methods are called
protocols. The most common protocol is Hypertext
Transfer Protocol (HTTP), which was originally created
to publish and view linked text documents, but has been extended
to display and run a growing variety of graphics, sound, video,
and other multimedia content. Other common protocols include File
Transfer Protocol (FTP), Gopher, telnet, RealAudio, as well as
protocols used to start other applications such as email
and Usenet newsreaders.
The following table describes many of the protocols commonly in
use today.
Uniform Resource Locators
To run or display Internet content with a Web browser, you type
an address called a Uniform Resource Locator
(URL) into its address box. You can enter a URL that points to
any Internet file type or resource supported by the browser that
will be used to display or run it. You enter most URLs in the
following format:
protocol://serveraddress/path
Protocol specifies the Internet protocol used
to establish the connection to the server, and is generally followed
by a colon and two slash marks. Serveraddress
specifies what is usually called the domain name
of the Internet server. Path specifies the
location and name of the page or file on the Internet server.
For example, this is the URL for the What's New page on the Microsoft
Access Developer Forum Web site:
http://www.microsoft.com/accessdev/whatsnew.htm
Note For
some protocols, URLs have a different format. For example, the
format for a URL that uses the MailTo protocol is mailto:username@domain;
the format for a URL that uses the News protocol is news:newsgroupname;
the format for a URL that uses the Network News Transfer Protocol
is nntp://newsgroupname.
Hypertext Markup Language and Hyperlinks
Most files you download and open with a Web browser are pages
formatted with Hypertext Markup Language (HTML) tags.
HTML tags are codes enclosed in angle brackets that are used by
a Web browser to determine the structure and appearance of an
HTML document, such as graphic elements and text formatting. For
example, the two HTML tags in the following sentence:
Make <B>this text</B> look bold.
Cause the text to display like this when viewed with a Web browser:
Make this text look bold.
To navigate to other pages or multimedia content, a user clicks
a hyperlink on a Web page. A hyperlink is colored
and underlined text, or a graphic, that uses the path specified
by a URL to download and open another file, such as another Web
page or some form of multimedia content, such as a picture or
sound file.
You can use HTML tags called anchors to create
hyperlinks. An anchor with an HREF attribute goes to a file outside
of the current document. For example, the following anchor creates
a hyperlink that goes to the Microsoft home page:
<A HREF="http://www.microsoft.com/">Microsoft
Home Page</A>
An anchor with a NAME attribute creates a bookmark at a location
within the same document. Other hyperlinks can go to the bookmark
created with this type of anchor.
HTML was originally a simple system for publishing documents on
the Web, but it's rapidly evolving to include features that you
can use to create sophisticated, interactive applications.
Tip You
can view an HTML reference that describes the most commonly used
HTML tags as well as recent additions supported by Microsoft Internet
Explorer and Netscape Navigator at http://www.microsoft.com/workshop/author/newhtml/.
Extensions to Standard Web Browser Functionality
Standard Web browser functionality is evolving through the addition
of a variety of new technologies such as helper applications,
plugins, ActiveX controls,
Java applets,
and scripting languages. If your Web browser
doesn't support these technologies, you may need to install additional
components to be able to use them.
Helper Applications
Helper applications are typically used to play audio or video
files, or to display certain graphic formats. You may need to
install helper applications before you can play or display certain
content in your Web browser. In more recent browsers, such as
Microsoft Internet Explorer version 3.0 and Netscape Navigator
version 3.0, many of these functions are built into the browser
itself, or are being replaced by one of the other technologies
described in this section.
PlugIns
By using plugins, Web page authors can embed content that
uses additional player or reader modules directly within Web pages.
For example, there are plugins used to display Macromedia
Director and Apple QuickTime® movies in
a Web page. In order to use Web pages containing content that
requires a plugin, the plugin must be installed beforehand.
Microsoft Internet Explorer version 3.0 and Netscape Navigator
versions 2.0 and 3.0 can run plugins.
ActiveX Controls
By using ActiveX controls, Web page authors can extend the kinds
of content that can be displayed on a Web page. They can also
enhance their Web pages with sophisticated formatting features,
animation, and embedded programs that perform operations such
as background downloading. ActiveX controls don't need to be installed
beforehand they can be downloaded when a user
first opens a Web page. Microsoft Internet Explorer version 3.0
has builtin support for Web pages that contain ActiveX controls.
To use a Web page that contains ActiveX controls in Netscape Navigator
version 3.0, you must use the NCompass ScriptActive plugin.
Java Applets
By using the Java programming language, Web page authors can produce
applications called applets, which can perform functions similar
to plugins and ActiveX controls. To display or run a Java
applet from a Web page, a Web browser must be able to compile
and run Java code. Microsoft Internet Explorer version 3.0 and
Netscape Navigator versions 2.0 and 3.0 can run Java applets.
Scripting Languages
Scripting languages are interpreted programming languages that
Web page authors can use to perform a variety of operations. They
are often used in conjunction with ActiveX controls or Java applets.
Three common examples of scripting languages are VBScript, JScript,
and JavaScript. To use a page that contains scripting language
code, a Web browser must be able to interpret the code. Microsoft
Internet Explorer version 3.0 can run both VBScript and JScript
code, as well as most JavaScript code. Netscape Navigator versions
2.0 and 3.0 can run JavaScript code. Netscape Navigator version
3.0 can run VBScript code if you have the NCompass ScriptActive
plugin installed.
In addition to scripting languages, there are a variety of serverside
scripting languages, such as CGI, PERL, and ActiveX
Scripting that extend the functionality of servers. In Microsoft
Access, you can create Active Server Pages (ASP) that use ActiveX
Scripting to bind data to Web page controls. By using Active Server
Pages, your Web pages can perform many of the same functions as
Microsoft Access forms.
Intranets
If you install Internet server software, such as Microsoft Internet
Information Server, on servers connected by a local area network
(LAN), you can use these same Internet technologies to share data
within an organization. Such a system is called an intranet
or internal Web. For example, your organization
could post human resources information for all employees on a
Web page, or a project team could post information about its members
and provide hyperlinks to important documentation about the project.
All the features in Microsoft Office that are designed for the
Internet can also be used on an intranet. For more information
about Microsoft Internet Information Server, see http://www.microsoft.com/ntserver/.
You can also set up a personal web server to
test your Web application or to publish smallscale intranet
applications. If you are using Windows 95, you can install
Microsoft Personal Web Server. If you are using Windows NT Workstation
version 4.0, you can install Microsoft Peer Web Services.
For more information about Personal Web Server or Peer Web
Services, see "Setting Up a Personal Web Server" later
in this chapter.
Protocol Protocol name
Description
http Hypertext Transfer Protocol
Goes to Web pages that contain text, graphics, sound, and other digital information from a Web server on the World Wide Web.
ftp File Transfer Protocol
Transfers files between computers on the Internet.
gopher Gopher protocol
Displays information on a Gopher server.
wais WAIS protocol
Accesses a Wide Area Information Servers database.
file File protocol
Opens a file on a local hard disk or LAN.
https Hypertext Transfer Protocol with privacy
Establishes an HTTP connection that uses Secure Sockets Layer (SSL) encryption.
mailto MailTo protocol
Opens your electronic mail program to send a message to the specified Internet e-mail address.
msn Microsoft Network protocol
Goes to a location on MSN, The Microsoft Network.
news News protocol
Starts a newsreader and opens the specified Usenet newsgroup.
nntp Network News Transfer Protocol
Performs the same function as News protocol.
mid Musical Instrument Digital Interface (MIDI) protocol
Plays MIDI sequencer files if the user's computer has a sound card.
cid CompuServe Dialer (CID) protocol
Establishes a point-to-point protocol (PPP) connection with the Internet through CompuServe's network.
prospero Prospero protocol
Opens files on the Prospero distributed file system.
telnet Telnet protocol
Starts a telnet terminal emulation program. A terminal emulation program is a command-line interface that you can use to issue commands on a remote computer. For example, by using telnet to connect to a UNIX server, you can issue UNIX commands to perform operations on that server.
rlogin Rlogin protocol
Starts an Rlogin terminal emulation program.
tn3270 TN3270 protocol
Starts a TN3270 terminal emulation program.
pnm RealAudio protocol
Plays RealAudio streaming audio from a RealAudio server. Streaming audio and other streaming media formats establish a connection to the server and start playing immediately without downloading an entire file.
mms Microsoft Media Server (MMS) protocol
Plays media such as ActiveMovie streaming format files (.asf) from an MMS server.
In all Microsoft Office 97 applications, you can create hyperlinks to display and run standard Internet content. Additionally, in all Office applications except Outlook, you can create hyperlinks to move between Microsoft Word documents, Microsoft Excel workbooks, Microsoft PowerPoint presentations, and Microsoft Access databases that are stored on a local hard disk or on a LAN. You don't need Internet connections or Web servers to use hyperlinks to move between Office documents or files. You can use both kinds of hyperlinks in the same application.
A hyperlink to a Microsoft Office document can also go to a specific location or object within another document or the current document. The following table lists the objects that a hyperlink can go to within each Microsoft Office application.
Application | Object |
Microsoft Access | A table in Datasheet view.A query in Datasheet view.A form in Form view or Datasheet view, depending on the form's DefaultView property setting.A report in Print Preview.A macro. Using a hyperlink to go to a macro runs the macro.A module. |
Microsoft Excel | A worksheet.A specified range of cells in a worksheet.A named range of cells in a worksheet. |
Microsoft PowerPoint | A slide. |
Microsoft Word | A bookmark. |
When you follow a hyperlink, either by clicking it or by using the Follow or FollowHyperlink method, the Office application may open a cached copy of the document, depending on the Internet settings in Control Panel. To view or change these settings, doubleclick the Internet icon in Control Panel, then click Settings on the Advanced tab. For more information about the Follow and FollowHyperlink methods, see "The Follow Method" and "The FollowHyperlink Method" later in this chapter.
Specifying a Hyperlink Address
When specifying a hyperlink address, you can use either of two
forms:
Specifying a URL as a Hyperlink Address
To create a hyperlink that goes to a Web page or other Internet
content, you must enter a valid URL as the hyperlink address.
You can enter a URL that points to any Internet file type or resource
supported by the browser or to an ActiveX control, such as the
WebBrowser control, that will be used to display or run it. For
example, the URL to the home page of the Microsoft Office Developer
Forum is:
http://www.microsoft.com/officedev/
When you enter a URL like the previous example that doesn't specify
a particular file name, be sure to include a slash mark (/) at
the end of the address. Although URLs that do not end in a slash
mark generally work, they require the server to perform additional
operations that add to the overall network load and slow down
the opening of the hyperlink. When you specify a file name at
the end of a URL, you do not end the URL with a slash mark. For
example:
http://www.microsoft.com/default.asp
If your users have Microsoft Internet Explorer version 3.0 or
if your application uses the WebBrowser control, your application
can open a Microsoft Excel workbook, Word document, or PowerPoint
presentation within the browser or control. To do this, the corresponding
Office application or viewer (Microsoft Excel Viewer, Word Viewer,
or PowerPoint Viewer) must also be installed on the user's computer.
In this case, a URL can point directly to an Office document on
a Web or intranet server. For example:
http://YourIntranetServer/YourWordDoc.doc
You can also open an Office document in Microsoft Internet Explorer
version 3.0 or in the WebBrowser control directly from the
standard file system, without using a Web server. To do so, use
the File protocol, as follows:
file://c:\my documents\sales.doc
Specifying a UNC or Standard Path as a Hyperlink Address
To create a hyperlink that starts a Microsoft Office 97 application
and opens one of its documents from a LAN, enter a universal naming
convention (UNC) path as the hyperlink address. This ensures that
the hyperlink continues to work if the document or the application
that contains the hyperlink is moved to another computer. A UNC
path starts with two backslashes (\\) and supplies the server
name, share name, and full path to the file. For example, a UNC
path to a Microsoft Excel workbook would be in the following format:
\\server\share\path\workbook.xls
You can also specify a network path that uses a mapped drive letter,
such as E:\path\workbook.xls.
However, because the path is specific to that drive letter, the
hyperlink only works if the user's computer has the drive letter
mapped to the appropriate server and share. If you want to create
a hyperlink that goes to a file on a local drive, you can use
a standard file path starting with a drive letter, such as C:\path\workbook.xls.
In this case, if the application is moved to another computer,
the hyperlink only works if the file specified in the address
is stored on the same drive and in the same folder on the new
computer.
You can also enter a UNC or standard file path as a hyperlink
address to open any file type that is registered on the computer
running your document or application. For example, if Notepad
is installed and registered to open text (.txt) files, you could
enter a UNC path to open a text file in the following format:
\\server\share\path\filename.txt
Absolute vs. Relative Links
When you create a hyperlink, you can use a path based on either
an absolute link or a relative link.
A path based on an absolute link points to a fixed file location.
Absolute links identify the destination of a hyperlink by its
full address such as C:\My Documents\Sales.doc or http:\\www.microsoft.com\default.htm.
Use an absolute link for hyperlinks to destinations that won't
be moved or that require a full path. For example, use absolute
links in hyperlinks to other Web sites, such as a list of your
favorite Web sites.
A path based on a relative link points to a destination relative
to the file the hyperlink is located in. When the first part of
the path is shared by both the file that contains the hyperlink
and the destination file, that part is called a hyperlink
base. For example, if the path to the file that contains
the hyperlink is C:\My Documents\Databases and the path to
the destination file is C:\My Documents\Workbooks, then C:\My
Documents is the hyperlink base. The hyperlink base address is
automatically added to the beginning of the path for all relative
links. You can specify the hyperlink base on the Summary
tab of the document's property sheet. To open a document's property
sheet in Microsoft Excel, Word, or PowerPoint, click Properties
on the File menu. To open the property sheet for a Microsoft Access
database, click Database Properties on the File
menu.
When a hyperlink uses a path based on a relative link, you can
move the file that contains the hyperlink and the destination
file without breaking the hyperlink if you move the destination
file to an identically named location. For example, if you set
the hyperlink base to C:\My Documents and then create a relative
link to a document in C:\My Documents\Workbooks, and you
move the document that contains the relative link to a new computer,
you must copy the destination file into an identically named folder
in C:\My Documents on the new computer. Alternatively, you can
move the destination file to a folder named Workbooks within another
folder (for example, D:\Applications), and then open the document
that contains the relative link and update the hyperlink base
to the new folder's name.
If you save a document or database object that contains relative
links as an HTML document, the hyperlink base is omitted from
the anchor tags created for those relative links. For example,
suppose you create a relative link to a database called Names.mdb
in C:\My Documents\Databases, and set the hyperlink base to C:\My Documents.
When you save the document as an HTML document, the anchor tag
created is <A HREF="Databases\Names.mdb">.
To keep the hyperlink from breaking in the HTML document, you
must create a Databases folder in the folder that contains the
HTML document on the HTTP server, and then copy the Names.mdb
database into that folder.
Using Objects and Collections to Work
with Hyperlinks
All Office 97 applications except Outlook provide objects
and collections that you can use to work with hyperlinks in Visual
Basic code. Although there are a great number of similarities
across each application, in some cases the objects and collections
that hyperlinks are associated with differ slightly in each Office
application.
To work with hyperlinks in Visual Basic code, you use the Hyperlink
object. In all Office 97 applications except Microsoft Access,
the Hyperlink object is a member of the Hyperlinks
collection. In Microsoft Access, the Hyperlink object is
a member of the Controls collection. The objects that can
contain a Hyperlinks collection differ for each application.
They are listed in the following table.
The objects that can have a Hyperlink object associated
with them differ for each application. The following table summarizes
which objects can have an associated Hyperlink object.
Adding New Hyperlink Objects to the Hyperlinks Collection
In Microsoft Excel and Word, use the Add method to create
a Hyperlink object and add it to the Hyperlinks
collection. To create a hyperlink with the Add method,
use the following syntax:
object.Add(anchor,
address, subaddress)
The following table describes the arguments of the Add
method.
Microsoft Word Examples
In Word, you can use the Add method to add a hyperlink
to either a Range object (a range or selection of text),
a Shape object (a graphic object), or an InlineShape
object (a graphic object within a line of text).
Creating a Hyperlink for a Microsoft Word Range Object
The following example inserts the text "Microsoft Web Site"
at the beginning of the active document, selects the inserted
text, and then adds a hyperlink to the text that goes to the Microsoft
home page at http://www.microsoft.com/.
Creating a Hyperlink for a Microsoft Word Shape Object
The following example creates a beveled shape, adds the text "Microsoft
Web Site" to the shape, and then adds a hyperlink to the
shape that goes to the Microsoft home page at http://www.microsoft.com/.
Creating a Hyperlink Associated with a Command Button
In addition to creating Hyperlink objects in Visual Basic
code, you can create a command button by using the user interface
and then add code to the command button's Click event procedure
to make it follow a hyperlink. This doesn't create a Hyperlink
object so the hyperlink isn't available in the document's Hyperlinks
collection. To create a command button that follows a hyperlink
in Microsoft Excel, Word, and PowerPoint, use the following procedure.
To
create a command button that follows a hyperlink
Note When
using this method, the command button doesn't display blue underlined
text or the hand cursor when the mouse is over the button.
For more information about the FollowHyperlink method,
see "The FollowHyperlink Method" later in this chapter.
Microsoft Excel Examples
In Microsoft Excel, you can use the Add method to add a
hyperlink to either a Range object (a range of one or more
cells) or a Shape object (a graphic).
Creating a Hyperlink for a Microsoft Excel Range Object
The following example adds the display text "MSN Web site"
to cell A1 in the first worksheet in the current workbook, and
then adds a hyperlink to that range that goes to the Web site
at http://www.msn.com/.
The following example adds a rounded rectangle labeled "Click
Here" to the first worksheet in the current workbook, and
then adds a hyperlink to the rectangle that goes to cell C6 on
the first sheet of Book2.xls.
Microsoft PowerPoint Examples
PowerPoint doesn't use the Add method to create a new hyperlink.
Instead, you create a hyperlink by working with the ActionSettings
collection of a Shape object (a graphic) or a TextRange
object (text associated with a Shape object). A Shape
or TextRange object can have two different hyperlinks assigned
to it: one that's followed when the user clicks the object during
a slide show, and another that's followed when the user passes
the mouse pointer over the object during a slide show.
To specify which mouse action to work with, first use the ActionSettings
property to return the ActionSettings collection, then
use ActionSettings(index), where index
is either ppMouseClick or ppMouseOver. Set the Action
property to ppActionHyperlink to specify that the action
is a hyperlink. After a hyperlink is created, it's available from
the Hyperlinks collections for the Shape, TextRange,
and Slide objects.
Creating a Hyperlink for a Microsoft PowerPoint Shape Object
The following example adds a Custom action button with text that
reads "Microsoft.com" to the first slide in the active
presentation, and then adds a hyperlink to the button that goes
to the Microsoft home page.
Creating a Hyperlink for a Microsoft PowerPoint TextRange
Object
The following example adds a rectangle to the first slide in the
active presentation, adds text to the rectangle, and then adds
a hyperlink to the text. This example defines a hyperlink for
all the text in the text range. It is possible to define more
than one hyperlink within a text range for selected characters.
Application
Objects that can contain a Hyperlinks collection
Microsoft Word Document, Range, or Selection objects
Microsoft Excel Worksheet or Range objects
Microsoft PowerPoint
Slide or Master objects
Microsoft Access None. Microsoft Access doesn't have a Hyperlinks collection. All Hyperlink objects are members of the Controls collection. In addition, you can have a set of records that contains fields with the Hyperlink data type and use Visual Basic to work with the records as if they were a collection.
Application
Objects that can have a Hyperlink object associated with them
Microsoft Word Shape, InlineShape, Selection, or Range objects
Microsoft Excel Shape, Selection, or Range objects
Microsoft PowerPoint
Shape.ActionSettings or TextRange.ActionSettings objects
Microsoft Access CommandButton, ComboBox, Image, Label, ListBox, or TextBox objects
Argument Description
object Required. An expression that returns a Hyperlink object.
anchor Required. The anchor for the hyperlink. Can be either a Range or a Shape object.
address Required. The address of the hyperlink.
subaddress Optional. The subaddress of the hyperlink.
Sub AddHyperlinkRange()
Dim r As Range
Set r = ActiveDocument.Range(Start := 0, End := 0)
r.InsertBefore "Microsoft Web Site"
Selection.MoveRight Unit := wdWord, Count := 3, Extend := wdExtend
ActiveDocument.Hyperlinks.Add Anchor := Selection.Range, _
Address := "http://www.microsoft.com/"
End Sub
Sub AddHyperlinkShape()
ActiveDocument.Shapes.AddShape(msoShapeBevel, 150, 150, 100, 30).Select
With Selection
.ShapeRange.TextFrame.TextRange.Select
.Collapse
.TypeText Text:="Microsoft Web Site"
.ShapeRange.Select
End With
ActiveDocument.Hyperlinks.Add Anchor:=Selection.ShapeRange, _
Address:= "http://www.microsoft.com/"
End Sub
Private Sub CommandButton1_Click()
FollowHyperlink "http://www.microsoft.com/"
End Sub
Creating a Hyperlink for a Microsoft Excel Shape Object
Sub AddHyperlink_Range()
Dim wrk As Worksheet
Set wrk = ActiveWorkbook.Sheets(1)
wrk.Range("A1").Value = "MSN Web site"
wrk.Hyperlinks.Add Address := "http://www.msn.com/", _
Anchor := wrk.Range("A1")
End Sub
Sub AddHyperlink_Shape()
Dim wrk As Worksheet
Dim shp As Shape
Set wrk = ActiveWorkbook.Sheets(1)
Set shp = wrk.Shapes.AddShape(msoShapeRoundedRectangle, 50, 50, 100, 50)
shp.Select
Selection.Characters.Text = "Click Here"
wrk.Hyperlinks.Add Anchor := shp, Address := "C:\My Documents\Book2.xls", _
SubAddress := "Sheet1!C6"
End Sub
Sub AddHyperlinkButton()
Dim sld As Slide, shp As Shape
Set sld = ActivePresentation.Slides(1)
Set shp = sld.Shapes.AddShape(msoShapeActionButtonCustom, 50, 50, 160, 30)
With shp.TextFrame
.TextRange.Text = "Microsoft.com"
.MarginBottom = 5
.MarginLeft = 5
.MarginRight = 5
.MarginTop = 5
End With
With shp.ActionSettings(ppMouseClick)
.Action = ppActionHyperlink
.Hyperlink.Address = "http://www.microsoft.com/"
End With
End Sub
Sub AddHyperlinkText()
Dim sld As Slide, shp As Shape, txt As Text
Set sld = ActivePresentation.Slides(1)
Set shp = sld.Shapes.AddShape(msoShapeRectangle, 0, 0, 250, 140)
shp.TextFrame.TextRange.Text = "Microsoft Web Site"
Set txt = shp.TextFrame.TextRange
With txt.ActionSettings(ppMouseClick)
.Action = ppActionHypertext
.Hyperlink.Address = "http://www.microsoft.com/"
End With
End Sub
Microsoft Access Example
Microsoft Access doesn't provide a Hyperlinks collection or use the Add method to create a hyperlink on a form or report. Instead, you create hyperlinks for label, command button, and image controls by setting either the HyperlinkAddress property or the HyperlinkSubAddress property, or both, of the control.
Note You
can also create a field with the Hyperlink data type to store
hyperlink addresses in a table, and then bind that field to a
text box, list box, or combo box on a form. For more information,
see "Storing Hyperlinks in Microsoft Access Tables"
later in this chapter.
Creating a Hyperlink Control in Microsoft Access
The following example creates a new label on a form and then sets
the HyperlinkAddress and HyperlinkSubAddress properties
to create a hyperlink. When you create a hyperlink in Visual Basic,
and you want it to be colored and underlined, you must also explicitly
set the ForeColor and FontUnderline properties.
Sub CreateHyperlinkLabel(strForm As String, xPos As Integer, _
yPos As Integer, strCaption As String, Optional strAddress As String, _
Optional strSubAddress As String)
Dim ctlLabel As Control
' Open form, hidden in Design view.
DoCmd.OpenForm strForm, acDesign,,,,acHidden
' Create label control with text specified by strCaption, at
' the position specified by xPos and yPos.
Set ctlLabel = CreateControl(strForm, acLabel, , "", _
strCaption, xPos, yPos)
' Set hyperlink address, text color, and underline.
With ctlLabel
.HyperlinkAddress = strAddress
.HyperlinkSubAddress = strSubAddress
.ForeColor = "1279872587"
.FontUnderline = True
End With
' Save form.
DoCmd.Save acForm, strForm
End Sub
To use this example to create a hyperlink, you must specify the form, position, display text, and hyperlink address. For example, enter the following code into the Debug window:
CreateHyperlinkLabel "Form1",100,100,"Microsoft Web Site","http://www.microsoft.com/"
You can use similar code to create image and command button controls and set properties to create a hyperlink.
Referring to Hyperlink Objects
Use the Hyperlink property to return a reference to a Hyperlink
object. The objects that can have a Hyperlink object associated
with them differ somewhat for each application.
Microsoft Word Example
Use the Hyperlink property to return the hyperlink for
a shape. Note that a shape can have only one hyperlink associated
with it. The following example follows the hyperlink associated
with the first shape in the active document.
ActiveDocument.Shapes(1).Hyperlink.Follow
Selection and Range objects can have multiple Hyperlink objects associated with them. For these objects, you must either loop through the object's Hyperlinks collection or specify a member of the object's Hyperlinks collection by using the Item method. The following example loops through the hyperlinks in the current selection.
Dim H As Hyperlink, hLinks As Hyperlinks
Set hLinks = Selection.Hyperlinks
For Each H In hLinks
MsgBox H.Address
Next H
The following example displays the address of the first hyperlink in the first 20 characters of the current document in the Immediate window.
Debug.Print ActiveDocument.Range(0,20).Hyperlinks(1).Address
Microsoft Excel Example
Use the Hyperlink property to return the hyperlink for a shape. Note that a shape can have only one hyperlink associated with it. The following example follows the hyperlink associated with the first shape on the first worksheet.
Worksheets(1).Shapes(1).Hyperlink.Follow NewWindow:=True
Microsoft PowerPoint Example
As mentioned earlier in this chapter, a shape in PowerPoint can have up to two different hyperlinks assigned to it: one that's followed when the user clicks the shape during a slide show, and another that's followed when the user passes the mouse pointer over the shape during a slide show. To return a hyperlink for a shape, you must first reference the appropriate member of the ActionSettings collection (ppMouseOver or ppMouseClick), and then use the Hyperlink property.
The following example displays the address for the mouseclick hyperlink of the third shape on the first slide of the active presentation in the Immediate window.
Debug.Print ActivePresentation.Slides(1).Shapes(3). _
ActionSettings(ppMouseClick).Hyperlink.Address
Microsoft Access Example
In Microsoft Access, you can use the Hyperlink property to return a reference to the Hyperlink object associated with a CommandButton, ComboBox, Image, Label, ListBox, or TextBox control.
The CreateHyperlink procedure in the following example sets the Address and SubAddress properties for a label, image control, or command button to the values passed to the procedure. The Address property setting is optional, because a hyperlink to a database object in the current database uses only the SubAddress property.
To try this example, create a form with two text box controls named txtAddress and txtSubAddress, and a command button named cmdFollowLink. Then paste the sample code into the Declarations section of the form's module. Display the form in Form view, enter appropriate values in the txtAddress and txtSubAddress text boxes, and click the cmdFollowLink button.
Private Sub cmdFollowLink_Click()
CreateHyperlink Me!cmdFollowLink, Me!txtSubAddress, Me!txtAddress
End Sub
Sub CreateHyperlink(ctlSelected As Control, txtSubAddress As TextBox, _
Optional txtAddress As TextBox)
Dim hlk As Hyperlink
Select Case ctlSelected.ControlType
Case acLabel, acImage, acCommandButton
Set hlk = ctlSelected.Hyperlink
With hlk
If Not IsMissing(txtAddress) Then
.Address = txtAddress
Else
.Address = ""
End If
.SubAddress = txtSubAddress
.Follow
.Address = ""
.SubAddress = ""
End With
Case Else
MsgBox "The control '" & ctlSelected.Name & "' does not support hyperlinks."
End Select
End Sub
Referring to a Hyperlink Object by Its Position in the Hyperlinks
Collection
Use the Item method (or the Item property in Microsoft
Excel) of the Hyperlinks collection to return a single
Hyperlink object based on its position in the collection.
The first object in the collection has an Item value of
1. The Item method is the default member of the Hyperlinks
collection, so you can refer to the Item method in either
of the following ways:
Hyperlinks.Item(1)
Hyperlinks(1)
Microsoft Word Example
The following example follows the first hyperlink in the selection.
If Selection.Hyperlinks.Count >= 1 Then
Selection.Hyperlinks(1).Follow
End If
Note The
Count property for the Hyperlinks collection of a Selection object
returns the number of items in the main story only. To count items
in other stories, specify the story in the StoryRanges collection.
For example, to count all of the hyperlinks in the primary footer
story you can use the following code.
ActiveDocument.StoryRanges(wdPrimaryFooterStory).Hyperlinks.Count.
Microsoft Excel Example
The following example uses the Follow method to activate
the second hyperlink in the range of cells from E5 to E8.
Worksheets(1).Range("E5:E8").Hyperlinks(2).Follow
Microsoft PowerPoint Example
The following example sets the Address property of the second hyperlink on the first slide in the current PowerPoint presentation.
ActivePresentation.Slides(1).Hyperlinks(2).Address = "C:\New\Newsales.ppt"
Looping Through the Hyperlinks Collection
You can use the Hyperlinks collection in Microsoft Excel,
Word, and PowerPoint to loop through the set of Hyperlink
objects associated with an object. In Microsoft Access, you can
loop through the Controls collection or a set of records
to work with the hyperlinks in your application.
The following examples perform operations on a Hyperlinks
collection that contains existing Hyperlink objects. In
the Microsoft Excel, Word, and PowerPoint examples that follow,
the object that contains the Hyperlinks collection is specific
to the application. However, you can modify each example to run
in another application by referring to the appropriate object.
Because the Microsoft Access examples use the Controls
collection or a set of records instead of the Hyperlinks
collection, you can only use them in Microsoft Access.
Microsoft Word Example
If the active document includes hyperlinks, this example inserts
a list of the hyperlink destinations at the end of the document.
Dim hLink As Hyperlink
Set myRange = ActiveDocument.Range(Start:=ActiveDocument.Content.End - 1)
Count = 0
For Each hLink In ActiveDocument.Hyperlinks
Count = Count + 1
With myRange
.InsertAfter "Hyperlink #" & Count & vbTab
.InsertAfter hLink.Address
.InsertParagraphAfter
End With
Next hLink
Microsoft Excel Example
The following example updates all hyperlinks on the first worksheet in the active workbook that have the specified address.
Dim hLink As Hyperlink
For Each hLink in ActiveWorkbook.Sheets(1).Hyperlinks
If LCase(hLink.Address) = "C:\Current Work\Sales.ppt" Then
hLink.Address = "C:\New\Newsales.ppt"
End If
Next hLink
Note In
Word, you can use the Hyperlinks collection to access hyperlinks
created by inserting a HYPERLINK field. In Microsoft Excel, however,
you cannot use the Hyperlinks collection to access hyperlinks
created by entering a formula using the HYPERLINK function.
Microsoft PowerPoint Example
The following example updates an outdated Internet address for
all hyperlinks in the active presentation.
Dim hLink As Hyperlink
Dim S As Slide
oldAddr = InputBox("Old internet address")
newAddr = InputBox("New internet address")
For Each S In ActivePresentation.Slides
For Each hLink In s.Hyperlinks
If LCase(hLink.Address) = Lcase(oldAddr) Then hLink.Address = newAddr
Next hLink
Next S
Microsoft Access Examples
Microsoft Access doesn't support the Hyperlinks collection, but you can loop through the Controls collection on a form or report to work with the hyperlinks associated with any control on the form or report. The following procedure displays the name and hyperlink address values for controls that contain hyperlinks in the Debug window.
Sub ListHyperlinks(strForm As String)
Dim Frm As Form
Dim Ctl As Control
DoCmd.OpenForm strForm, acDesign, , , , acHidden
Set Frm = Forms(strForm)
' Ignore controls without hyperlinks.
On Error Resume Next
For Each Ctl In Frm.Controls
If Not (Ctl.ControlType = acTextBox) Then
Debug.Print "Control:" & Ctl.Name & vbCrLf & _
"Address:" & Ctl.Hyperlink.Address & vbCrLf & _
"Subaddress:" & Ctl.Hyperlink.SubAddress & vbCrLf
Else
Debug.Print "Control:" & Ctl.Name & vbCrLf & _
"Text box control bound to Hyperlink field " & _
Ctl.ControlSource & vbCrLf
End If
Next Ctl
Frm.Close
End Sub
In addition to creating Hyperlink objects that belong to the Controls collection of forms and reports, you can have a set of records that contains fields with the Hyperlink data type and use Visual Basic to work with the records as if they were a collection. For example, you can loop through the records in a table to work with the properties of a field. The following procedure works with the Suppliers table in the Northwind sample database. If a field is a Hyperlink field, the procedure loops through all the records in the table. If a field is not null (empty), it displays the record number, field name, and displayed value in the Debug window.
Sub HyperlinkRecordset()
Dim dbs As Database
Dim rstSuppliers As Recordset
Dim fldField As Field
' Return reference to current database.
Set dbs = CurrentDb
' Create dynaset-type Recordset object.
Set rstSuppliers = dbs.OpenRecordset("Suppliers", dbOpenDynaset)
' Print displayed value for fields containing hyperlinks.
For Each fldField In rstSuppliers.Fields
If (fldField.Attributes And dbHyperlinkField) Then
With rstSuppliers
Do While Not .EOF
If Not IsNull(fldField.Value) Then
Debug.Print rstSuppliers.AbsolutePosition + 1 & " " & _
fldField.Name & " " & _
HyperlinkPart(fldField.Value, acDisplayedValue)
End If
.MoveNext
Loop
.MoveFirst
End With
End If
Next fldField
' Free all object variables.
rstSuppliers.Close
Set dbs = Nothing
End Sub
For more information about Hyperlink fields, see "Storing Hyperlinks in Microsoft Access Tables" later in this chapter.
Using Methods and Properties to Work with
Hyperlinks
The following table summarizes the methods and properties you
can use to work with hyperlinks in Visual Basic.
msoHyperlinkInlineShape (Word only)
For more information about these methods and properties, search
Help in the appropriate application for the name of the method
or property.
The Follow Method
The Follow method follows a hyperlink defined by an existing
Hyperlink object, and has the same effect as clicking the
hyperlink. The Follow method downloads the document or
Web page specified by the hyperlink address associated with a
Hyperlink object and opens it in the appropriate application.
If the hyperlink refers to a file system path or uses the File
protocol, the Follow method opens the document instead
of downloading it.
The syntax for the Follow method is:
expression.Follow(newwindow,
addhistory, extrainfo, method,
headerinfo)
The following table describes the arguments of the Follow
method.
"string1" & vbCr & "string2"
The specified string is automatically converted into ANSI characters. Note that the headerinfo argument may overwrite default HTTP header fields.
For the method argument of the Follow
method, you can specify one of the constants described in the
following table.
http://www.web.com/cgi-bin/srch?item1+item2
item1+item2 is the extra information that's passed to the srch program on the HTTP server.
name1=value1&name2=value2
This data can be submitted as either a string or byte array, depending on what format the program on the server has been programmed to use. Use the HTTP POST method to submit extra information if the program on the HTTP server is reading the form's data from the standard input stream (STDIN).
For examples that illustrate uses of the Follow method,
see the code samples in previous sections of this chapter.
The FollowHyperlink Method
The FollowHyperlink method follows a hyperlink address
specified in code or passed to the method from a variable or object.
For example, you can prompt a user to type a hyperlink address
in a dialog box, and then use the FollowHyperlink method
to go to that address. The FollowHyperlink method downloads
the document or Web page specified by the hyperlink address associated
with a Hyperlink object and opens it in the appropriate
application. If the address refers to a file system path or uses
the File protocol, the FollowHyperlink method opens the
document instead of downloading it.
The syntax for the FollowHyperlink method is:
expression.FollowHyperlink(address,
subaddress, newwindow, addhistory,
extrainfo, method, headerinfo)
The following table describes the arguments of the FollowHyperlink
method.
Microsoft Word Document objectMicrosoft Excel Workbook objectMicrosoft PowerPoint Presentation objectMicrosoft Access Application object
For information about the newwindow, addhistory,
extrainfo, method, and headerinfo
arguments, see the preceding section, "The Follow
Method."
Microsoft Word Examples
This example follows the specified URL and displays the Microsoft
home page in a new window.
This example opens the HTML document named Default.htm directly
from the local hard disk.
Microsoft Excel Example
This example follows the specified URL address and displays the
names of all the topics related to opera.
Method or property name
Description
Hyperlink property
Returns a reference to a hyperlink object in code.
Follow method
Follows a hyperlink defined by an existing Hyperlink object. The Follow method has the same effect as clicking the hyperlink.
FollowHyperlink method
Follows a hyperlink address specified in code or passed to the method from a text box. For example, you can prompt a user to type a hyperlink address in a dialog box or form, and then use the FollowHyperlink method to go to that address.
ExtraInfoRequired property(Word only)
A read-only property that returns True if extra information is required to resolve the specified hyperlink. You can specify extra information, such as a file name or a query string, by using the extrainfo argument with the Follow or FollowHyperlink methods.
AddToFavorites method
Adds a shortcut to the Favorites folder. The AddToFavorites method can reference a Hyperlink object or the current document (Microsoft Access database, Microsoft Excel workbook, Microsoft PowerPoint presentation, or Microsoft Word document).
Address property
Returns the address of the specified hyperlink. This property is read/write, except in Word, where it is read-only.
Subaddress property
Returns a named location in the destination of the specified hyperlink. The named location can be a bookmark (Microsoft Word), a named cell or cell reference (Microsoft Excel), a database object (Microsoft Access), or a slide number (Microsoft PowerPoint). This property is read/write, except in Word, where it is read-only.
Type property (Microsoft Excel, Word, and PowerPoint only)
Returns the type of object the hyperlink is associated with. Can be one of the following constants:
msoHyperlinkRange
msoHyperlinkShape
HyperlinkAddress property(Microsoft Access only)
Sets or returns the address of a hyperlink for a label, image control, or command button. The HyperlinkAddress property is equivalent to setting or returning the Address property for the control in Visual Basic; for example, object.HyperlinkAddress is equivalent to object.Hyperlink.Address. You can also set the HyperlinkAddress property in the control's property sheet.
HyperlinkSubAddress property(Microsoft Access only)
Sets or returns the location within the Office document or object specified by the HyperlinkAddress property. When no HyperlinkAddress property is specified, HyperlinkSubAddress specifies a database object in the current database.
The HyperlinkSubAddress property is equivalent to setting or returning the SubAddress property for the control in Visual Basic; for example, object.HyperlinkSubAddress is equivalent to object.Hyperlink.SubAddress. You can also set the HyperlinkSubAddress property in the control's property sheet.
Argument Description
expression Required. An expression that returns a Hyperlink object.
newwindow Optional. A Boolean value where True ( 1) opens the document in a new window and False (0) opens the document in the current window. The default value is False.
addhistory Optional. A Boolean value where True ( 1) adds the hyperlink to the History folder and False (0) doesn't add the hyperlink to the History folder. The default value is True.
extrainfo Optional. A string or an array of Byte data that specifies additional information for HTTP to use to resolve the hyperlink.
For example, you can use the extrainfo argument to specify the coordinates of an image map or the contents of a form. The string is either appended or posted, depending on the value of the method argument. In Word, you can use the ExtraInfoRequired property to determine whether extra information is required.
method Optional. Specifies the way the extrainfo argument is handled. You can set the method argument to msoMethodGet or msoMethodPost.
headerinfo Optional. A string that specifies header information for the HTTP request. The default value is a zero-length string (" "). You can combine several header lines into a single string by using the following syntax:
Constant Description
msoMethodGet
The extrainfo argument is a string that's appended to the URL, separated by a question mark, when you use the HTTP GET method from an HTML form. For example, you can submit a query to an HTTP server by using an address in the following format:
msoMethodPost
The extrainfo argument is posted to the server as a string or a byte array when you use the HTTP POST method. For example, data from a form is typically submitted to an HTTP server with a series of name/value pairs in the following format:
Argument Description
expression Required. An expression that returns one of the following objects:
address A string expression that evaluates to a valid hyperlink address.
subaddress A string expression that evaluates to a named location in the document specified by the address argument. The default is a zero-length string (" "). If no address is specified, subaddress specifies a named location in the document or database.
ActiveDocument.FollowHyperlink Address:="http://www.microsoft.com", _
NewWindow:=True, AddHistory:=True
ActiveDocument.FollowHyperlink Address:="file://C:\Pages\Default.htm"
ActiveWorkbook.FollowHyperlink Address:="http://search.Yahoo.com/bin/search", _
AddHistory:=False, Method:=msoMethodGet, ExtraInfo:="p=Opera"
Microsoft PowerPoint Example
This example loads the document at www.gohere.com in a new window and adds it to the History folder.
Application.ActivePresentation.FollowHyperlink _
Address:="http://www.gohere.com", NewWindow:=True, AddToHistory:=True
Microsoft Access Examples
The following function prompts a user for a hyperlink address and then follows the hyperlink.
Function GetUserAddress() As Boolean
Dim strInput As String
On Error GoTo Error_GetUserAddress
strInput = InputBox("Enter a valid address")
Application.FollowHyperlink strInput, , True
GetUserAddress = True
Exit_GetUserAddress:
Exit Function
Error_GetUserAddress:
MsgBox Err & ": " & Err.Description
GetUserAddress = False
Resume Exit_GetUserAddress
End Function
You can call this function with a procedure such as the following.
Sub CallGetUserAddress()
If GetUserAddress = True Then
MsgBox "Successfully followed hyperlink."
Else
MsgBox "Could not follow hyperlink."
End If
End Sub
In Microsoft Access, you can also use the FollowHyperlink method to specify a hyperlink for controls that don't support the HyperlinkAddress or HyperlinkSubAddress properties (controls other than labels, image controls, and command buttons, or text boxes bound to Hyperlink fields).
This example uses the FollowHyperlink method to add hyperlink behavior to an unbound object frame control. Add the following code to the Click event of an unbound object frame named OLEUnbound1 to start a Web browser and open the specified hyperlink address when you click the image.
Note
You can use similar code in Microsoft Excel, Word, or PowerPoint
to create a command button that follows a hyperlink. To do so,
add a command button by using the Control Toolbox, and then define
a Click event procedure for the button. For more information,
see "Creating a Hyperlink Associated with a Command Button"
earlier in this chapter.
Private Sub OLEUnbound1_Click()
Dim strAddress As String
On Error GoTo Error_OLEUnbound1
' Set reference to hyperlink address.
strAddress = "http://www.microsoft.com/"
' Follow hyperlink address.
Application.FollowHyperlink strAddress, , True
Exit_OLEUnbound1:
Exit Sub
Error_OLEUnbound1:
MsgBox Err & ": " & Err.Description
Resume Exit_OLEUnbound1
End Sub
Tip Using the FollowHyperlink method to add hyperlinks to controls that don't support the HyperlinkAddress or HyperlinkSubAddress properties doesn't provide any feedback to the user to indicate that the control can follow a hyperlink. One way to inform a user that the control contains a hyperlink is to set the control's ControlTipText property so that a text message appears when the user rests the pointer on the control.
Handling Hyperlink Errors
If an error occurs when using the Follow or FollowHyperlink
methods in Visual Basic, an Automation error is displayed that
contains only an error number in both decimal and hexadecimal
format. For example, if xyz.htm doesn't exist, and you run the
following code in Microsoft Access:
Application.FollowHyperlink "http://www.microsoft.com/xyz.htm"
the error message shown in the following illustration occurs.
This error number indicates that the requested item could not be found.
You can prevent these error messages from being displayed to users of your application. To do so, check the Number property of the Err object against a decimal value in the table that follows. Then handle the error by either returning an appropriate message or performing a suitable action. If you want to be certain that all errors are handled, write an error handler that traps the entire set of error numbers.
Function GetUserAddress() As Boolean
Dim strInput As String
Dim lngErrNumber As Long
On Error GoTo Error_GetUserAddress
strInput = InputBox("Enter a valid address")
Application.FollowHyperlink strInput, , True
GetUserAddress = True
Exit_GetUserAddress:
Exit Function
Error_GetUserAddress:
' Set variable equal to error number.
lngErrNumber = Err.Number
' Check variable against all possible error numbers.
Select Case lngErrNumber
Case -2146697211
MsgBox "Cannot locate the Internet server or proxy server."
Case -2146697210
MsgBox "The site reports that the item you requested " _
& "could not be found. (HTTP/1.0 404)"
.
. ' Repeat for all possible error numbers.
.
End Select
GetUserAddress = False
Resume Exit_GetUserAddress
End Function
The following table lists the error numbers and descriptions for all errors that can occur when using the Follow and FollowHyperlink methods.
Decimalerror number | Hexadecimalerror number | Description |
2146697214, 2147221020 and 2147012891 | 0x800C0002, 0x800401E4 and 0x80072EE5 | The address of this site is not valid. Check the address and try again. |
2146697213 | 0x800C0003 | Cannot start an Internet session. |
2146697212 and 2147012867 | 0x800C0004 and 0x80072EFD | Cannot connect to the Internet server. |
2146697211 | 0x800C0005 | Cannot locate the Internet server or proxy server. |
2146697210 and 2147012868 | 0x800C0006 and 0x80072EFC | The site reports that the item you requested could not be found. (HTTP/1.0 404) |
2146697209 | 0x800C0007 | The Internet site reports that a connection was established but the data is not available. |
2146697208 | 0x800C0008 | Cannot download the information you requested. |
2146697207 | 0x800C0009 | The item you requested requires proper authentication. (HTTP/1.0 401) |
2146697206 | 0x800C000A | The Internet site cannot return the object you requested. (HTTP/1.0 403) |
2146697205 and 2147012894 | 0x800C000B and 0x80072EE2 | The connection to this Internet site took longer than the allotted time. |
2146697204 | 0x800C000C | The site reports that the request is not valid. |
2146697203 and 2147012888 | 0x800C000D and 0x80072EE8 | The required Internet protocol is not installed on your computer, or the Internet address you requested may not be valid. |
2146697202 | 0x800C000E | A security problem has occurred. |
2146697201 and 2147221014 | 0x800C000F and 0x800401EA | Cannot open the specified file. |
2146697200 | 0x800C0010 | Cannot start the program needed to open this file. |
2147221018 and 2147221164 | 0x800401E6 and 0x80040154 | No program is registered to open this file. |
2147467260 | 0x80004004 | The hyperlink cannot be followed to the destination. |
Note In
PowerPoint, one error number is returned for all Follow or FollowHyperlink
method errors: 2147467259 (0x80004005).
The AddToFavorites Method
The AddToFavorites method adds a shortcut to the Favorites
folder in the Windows program folder.
The syntax for the AddToFavorites method is:
expression.AddToFavorites
Expression is an expression that returns either
a Hyperlink object or one of the objects listed in the
following table.
When referring to a Hyperlink object, the shortcut is the
friendly name of the document. The friendly name is determined
by the text in the <TITLE> HTML tag. If the document
doesn't have a friendly name, the shortcut name is resolved by
the application. If there is an existing shortcut of the same
name, it is overwritten without notification.
Microsoft Word Examples
In Word, the shortcut created by the AddToFavorites method
can refer to a Document object or to a Hyperlink
object.
The following example creates a shortcut to Sales.doc and adds
it to the Favorites folder. If Sales.doc isn't currently open,
Word opens it from the C:\My Documents folder.
To add an existing hyperlink in the document to the Favorites
folder, you must refer to the document's Hyperlinks collection.
The following example adds all of the hyperlinks in the document
to the Favorites folder.
Application
Object Microsoft Word Document
Microsoft Excel Workbook
Microsoft PowerPoint
Presentation Microsoft Access
Application Sub AddDocument()
Dim isOpen As Boolean, doc As Document
For Each doc In Documents
If LCase(doc.Name) = "Sales.doc" Then isOpen = True
Next doc
If isOpen <> True Then Documents.Open _
FileName:="C:\My Documents\Sales.doc"
Documents("Sales.doc").AddToFavorites
End Sub
Sub AddHyperlinks()
Dim H As Hyperlink
Dim Hlinks As Hyperlinks
Set Hlinks = ActiveDocument.Hyperlinks
For Each H In Hlinks
H.AddToFavorites
Next H
End Sub
Microsoft Excel Examples
In Microsoft Excel, the shortcut created by the AddToFavorites method can refer to a Workbook object or to a Hyperlink object.
To create a shortcut to the current workbook and add it to the Favorites folder, use the following code.
ActiveWorkbook.AddToFavorites
To add an existing hyperlink in the current workbook to the Favorites folder, you must refer to the workbook's Hyperlinks collection. For example, to create a shortcut to the address in the first hyperlink in the active workbook and add it to the Favorites folder, use the following code.
ActiveWorkbook.Sheets(1).Hyperlinks(1).AddToFavorites
Microsoft PowerPoint Examples
In PowerPoint, the shortcut created by the AddToFavorites method can refer to a Presentation object or to a Hyperlink object.
To add a shortcut to the current presentation, use the following code.
Application.ActivePresentation.AddToFavorites
To add a hyperlink in the current slide to the Favorites folder, you must refer to the slide's Hyperlinks collection. The following example adds all of the hyperlinks on the first slide of the current presentation to the Favorites folder.
Sub AddHyperlinks()
Dim H As Hyperlink
Dim Hlinks As Hyperlinks
Set Hlinks = ActivePresentation.Slides(1).Hyperlinks
For Each H In Hlinks
H.AddToFavorites
Next H
End Sub
Microsoft Access Examples
In Microsoft Access, the shortcut created by the AddToFavorites method can refer to the Application object, which represents the current database, or to a hyperlink associated with a Control object.
To create a shortcut to the current database and add it to the Favorites folder, use the following code.
Application.AddToFavorites
To refer to a hyperlink associated with a Control object, you must use the Hyperlink property to access the Hyperlink object. For example, to create a shortcut to a hyperlink defined for a command button named Command0 on the current form and add it to the Favorites folder, use the following code.
Me!Command0.Hyperlink.AddToFavorites
Storing Hyperlinks in Microsoft Access
Tables
In Microsoft Access 97, you can create a field with the Hyperlink
data type to store hyperlink addresses in a table. You can follow
a hyperlink stored in a Microsoft Access table by clicking it
in the table. However, typically the field is bound to a text
box, list box, or combo box control on a form. Like other bound
fields, as the user moves from record to record, the value in
the control changes to display the current record's hyperlink
value. For example, you can use hyperlinks in this way to create
an application in which users can go to Web pages, or to other
content on the Internet or an intranet, from a predefined list
of addresses.
In addition to storing hyperlinks to Internet addresses, you can
also use hyperlinks in Microsoft Access to go to database objects
and other Office documents. For example, you could create a document
management application that uses a Hyperlink field to store paths
to Word documents on a network. Users of such an application could
add records to track new documents, or click the hyperlink in
a previously added record to open the specified document.
To create a Hyperlink field, add a field in table Design view
and set its DataType property to Hyperlink. You can also
create a Hyperlink field in table Datasheet view by clicking Hyperlink
Column on the Insert menu.
The Hyperlink Field Storage Format
In Microsoft Access, a Hyperlink field stores up to three pieces
of information: the displaytext, the address,
and the subaddress. Each piece is separated
by a pound sign (#), in the following format:
displaytext#address#subaddress
The following table describes each piece of the Hyperlink field
storage format.
Each piece of the Hyperlink field storage format can be up to
2,000 characters. The maximum length of the entire Hyperlink field
value is 6,000 characters.
The following table gives examples of valid Hyperlink field values.
You can enter data in a Hyperlink field in three ways: by using
the Insert Hyperlink dialog box (available through the
Hyperlink command on the Insert menu), by typing
an address directly into a Hyperlink field, or by using Data Access
Objects (DAO) methods in Visual Basic code. When you use the Insert
Hyperlink dialog box or type directly into a Hyperlink field,
Microsoft Access adds the two pound signs (#) that delimit the
parts of the hyperlink data. When you use DAO methods, your code
must include the two pound signs to delimit the parts of the hyperlink
data.
You can display the stored hyperlink format in a table by moving
the insertion point into a Hyperlink field using the keyboard,
and then pressing F2. You can edit the stored
hyperlink in this form, but be careful to enter pound signs in
the appropriate locations. You can add or edit the displaytext
part of a Hyperlink field by rightclicking a hyperlink in
a table, pointing to Hyperlink on the shortcut menu, and
then typing the display text in the Display Text box. You
can add or edit the address or subaddress
part of a Hyperlink field by rightclicking a hyperlink in
a table, pointing to Hyperlink on the shortcut menu, and
then selecting Edit Hyperlink.
The HyperlinkPart Function
The HyperlinkPart function returns information about data
stored in a Hyperlink field. The syntax for the HyperlinkPart
function is:
object.HyperlinkPart(hyperlink
As Variant, part As Integer)
The following table describes the arguments of the HyperlinkPart
function.
You can set the part argument to the following
constants.
Note If
you use the HyperlinkPart function in an SQL statement or a query,
the part argument is required and you can't set it to the constants
listed in the preceding table you must use the
value instead.
You use the HyperlinkPart function to return one of three
values stored in a Hyperlink field (displaytext,
address, or subaddress)
or the displayed value. The value returned depends on the setting
of the part argument. If you don't use the
part argument, the HyperlinkPart function
returns the value Microsoft Access displays for the hyperlink
(which corresponds to the acDisplayedValue setting for
the part argument).
When a value is provided in the displaytext
part of a Hyperlink field, the value displayed by Microsoft Access
will be the same as the displaytext setting.
When there's no value in the displaytext part
of a Hyperlink field, Microsoft Access displays the value of the
address or subaddress part
of the Hyperlink field, depending on which value is first present
in the field.
The following table shows the values returned by the HyperlinkPart
function for data stored in a Hyperlink field.
The following example uses all four of the part
argument constants to display information returned by the HyperlinkPart
function for each record in a table containing a Hyperlink field.
To try this example, paste the DisplayHyperlinkParts procedure
into the Declarations section of a module. You can call the DisplayHyperlinkParts
procedure from the Debug window, passing to it the name of a table
that contains hyperlinks and the name of the field that contains
Hyperlink data, as shown in the following example.
When you use the HyperlinkPart function in a query, the
part argument is required. For example, the
following SQL statement uses the HyperlinkPart function
to return information about data stored as a Hyperlink data type
in the URL field of the Links table:
For another example of using the HyperlinkPart function,
see "Displaying a Document in the WebBrowser Control by Using a Hyperlink Stored in a Table" later in this chapter.
Following a Hyperlink in a Text Box Bound to a Hyperlink Field
When you use the Follow method in Microsoft Access, you
don't need to know the address specified by a control's HyperlinkAddress
or HyperlinkSubAddress property, or by the Hyperlink field
that is bound to a text box, list box, or combo box control. You
only need to know the name of the control that contains the hyperlink.
This example uses the Follow method to automatically open
the Web page specified in a text box bound to a Hyperlink field
on a form whenever the user moves to a new record. Add the following
code to the OnCurrent event of a form.
For another example of following a hyperlink stored in a table,
see "Displaying a Document in the WebBrowser Control by Using a Hyperlink Stored in a Table" later in this chapter.
Creating a Hyperlink Field with Visual Basic
You can use Data Access Objects (DAO) code to create a field with
the Hyperlink field type. To do so, you must first create a field
with the Memo data type and then set the Attributes property
of the field to dbHyperlinkField. The following example
creates a table named Hyperlinks that contains a Text field and
a Hyperlink field.
All of the Office 97 applications provide ways to save their
data as HTML documents. Microsoft Access and Word provide ways
of doing so by using Visual Basic.
Saving Microsoft Access Data as HTML Documents
Microsoft Access has five ways to save data from your database
as HTML documents:
Save data as static HTML documents You
can create static HTML documents from table,
query, and form datasheets, and from reports. When you save data
as static HTML documents, the resulting pages reflect the state
of the data at the time it was saved, like a snapshot. If your
data changes, you must save the pages again to share the new data.
Save table, query, and form datasheets as IDC/HTX files You
can save your table, query, and form datasheets as Internet Database
Connector/HTML extension (IDC/HTX) files that generate HTML documents
by querying a copy of your database located on a Web server for
current data.
Save forms and datasheets as Active Server Pages You
can save your forms as Active Server Pages (ASP) that emulate
most of the functionality of your forms and display data from
a database located on a Web server. You can also save table, query,
and form datasheets as Active Server Pages that display current
data from a copy of your database located on a Web server.
Automate the publishing of dynamic and static HTML documents
by using the Publish to the Web Wizard You
can use the Publish to the Web Wizard to automate the process
of saving multiple objects to any combination of all three file
types. In the Publish to the Web Wizard, IDC/HTX files and Active
Server Pages (ASP) files are collectively referred to as dynamic
Web pages because these file types create HTML documents by querying
the database to include current data.
Automate the publishing of dynamic and static HTML documents
by using the OutputTo method or action You
can use the OutputTo method in Visual Basic and the OutputTo
action in macros to automate the process of saving objects to
any of the three file types.
The following sections discuss each of these options in more detail.
Saving Data as Static HTML Documents
With Microsoft Access, you can save table, query, and form datasheets,
and reports as static HTML documents.
To
save a table, query, or form datasheet, or a report as a static
HTML document
For information about HTML templates, see "Using
an HTML Template When You Save Data as HTML Documents" later
in this chapter.
You can also save data as static HTML documents by using the Publish
to the Web Wizard (available through the Save As HTML command
on the File menu), the OutputTo method in code,
or the OutputTo action in macros. For information about using
the OutputTo method, see "Saving HTML Documents by Using the OutputTo Method" later in this chapter.
When saving table, query, and form datasheets, Microsoft Access
saves each datasheet to a single HTML file. Microsoft Access saves
reports as multiple HTML documents, with one HTML file per printed
page. To name each page, Microsoft Access uses the name of the
object and appends _Pagenn to the end of each
page's file name after the first page; for example, ProductList.htm,
ProductList_Page2.htm, ProductList_Page3.htm, and so on.
Saving Table, Query, and Form Datasheets as Static HTML Documents
When you save a table, query, or form datasheet as an HTML document,
the HTML document generated is based on the table or query associated
with the datasheet, including the current setting of the OrderBy
or Filter property of the table or query. If the datasheet
contains a parameter query, Microsoft Access first prompts you
for the parameter values, then exports the results.
If you select the Save Formatted check box, the HTML document
contains an HTML table that reflects as closely as possible the
appearance of the datasheet by using the appropriate HTML tags
to specify color, font, and alignment. The HTML document follows
as closely as possible the page orientation and margins of the
datasheet. Whenever you want to use settings that are different
from the default orientation and margins for a datasheet, you
must first open the datasheet, and then use the Page Setup
command (File menu) to change settings before you save
the datasheet as an HTML document.
If you select the Save Formatted check box, and a field
has a Format or InputMask property setting, those
settings are reflected in the data in the HTML document. For example,
if a field's Format property is set to Currency, the data
in the HTML document is formatted with a dollar sign, a comma
as the thousand separator, and two decimal places; for example,
$1,123.45.
Saving Reports as Static HTML Documents
When you save a report as HTML documents, the series of HTML documents
generated is based on the report's underlying table or query,
including the current OrderBy or Filter property
settings of the table or query. If the report contains a parameter
query, Microsoft Access first prompts you for the parameter values,
then exports the results.
The HTML documents simulate as closely as possible the appearance
of the report by creating the appropriate HTML tags to retain
attributes such as color, font, and alignment. The proportions
and layout of the actual report follow as closely as possible
the page orientation and margins set for the report. To change
the page orientation and margins, open the report in Print Preview,
and then use the Page Setup command to change settings
before you save the report as HTML documents. These settings are
saved from session to session for reports, so if you change them
once, they will be used the next time you save the form or report
as HTML documents.
Most controls and features of a report, including subreports,
are supported except the following: lines, rectangles, OLE objects,
and subforms. However, you can use an HTML template file to include
report header and footer images in your output files. For an example,
see the Nwindtem.htm template file in the C:\Program Files\Microsoft Office\Office\Samples
folder.
Navigation Controls When Saving Multiple HTML Documents Per
Object
If you specify an HTML template that contains placeholders for
navigation controls when you save a report as multiple HTML documents,
Microsoft Access creates hyperlinks that the user can use to go
to the first, previous, next, and last pages in the publication.
Where Microsoft Access places the hyperlinks depends on where
you locate the placeholders in the HTML template. For information
about HTML templates and placeholders, see "Using an HTML Template When You Save Data as HTML Documents" later in this
chapter.
How Microsoft Access Saves Data Types in HTML Format
When you save data as static HTML documents, Microsoft Access
saves values from most data types as strings and formats them
as closely as possible to their appearance in the datasheet or
report. All unformatted data types, except Text and Memo, are
saved with right alignment as the default. Text and Memo fields
are saved with left alignment by default.
There are two exceptions:
Microsoft Access determines the displaytext,
address, and subaddress
values by parsing the value stored in the Hyperlink field. For
information about the displaytext, address,
and subaddress values, see "The Hyperlink
Field Storage Format" earlier in this chapter.
Using an HTML Template When You Save Data as HTML Documents
When you save data as HTML documents, you can use an HTML template
to give a consistent look to the HTML documents you create. For
example, you can include your company's logo, name, and address
in the page's header, use the background that is used throughout
your company, or include standard text in the header or footer
of the HTML document.
Note You
can use an HTML template when you save data as static HTML documents,
when you save datasheets as IDC/HTX files, when you save a form
or datasheet as an Active Server Page, and when you use the Publish
to the Web Wizard.
The HTML template can be any HTML document; that is, a text file
that includes HTML tags and userspecified text and references.
In addition, the HTML template can include placeholders that tell
Microsoft Access where to insert certain pieces of data in the
HTML documents. When data is saved as HTML documents, the placeholders
are replaced with data. The following table describes each of
the placeholders that you can use in an HTML template.
When you install Microsoft Access, sample HTML template files
and graphics files are installed in the Access subfolder of the
Templates folder. The default location of this folder is C:\Program
Files\Microsoft Office\Templates\Access.
Saving Table, Query, and Form Datasheets as IDC/HTX Files
With Microsoft Access, you can save a table, query, or form datasheet
as Internet Database Connector/HTML extension (IDC/HTX)
files that generate HTML documents by querying a copy of your
database located on a Web server. In contrast to static HTML documents,
which contain the data that was current at the time the HTML document
was created, IDC/HTX files generate an HTML page with current
data from your database; therefore, the HTML documents that they
generate are called dynamic.
To
save a table, query, or form datasheet as IDC/HTX files
Note You
can specify any of these items later, except the HTML template,
by editing the resulting IDC file in a text editor such as Notepad.
If the datasheet contains a parameter query, Microsoft Access
simulates the Enter Parameter Value dialog box by creating
an additional HTML parameter page that contains an HTML form text
box control to enter the parameter value and a button to run the
query. You must display this HTML parameter page before you display
the datasheet HTML page in your Web application. If you use the
Publish to the Web Wizard and you specify a switchboard page,
the HTML parameter page is added to the switchboard page. When
you export, Microsoft Access runs the query and displays the Enter
Parameter Value dialog box. You don't need to enter values
in this dialog box just click OK to continue.
You can also save a table, query, or form datasheet as IDC/HTX
files by using the Publish to the Web Wizard (available through
the Save As HTML command on the File menu), the
OutputTo method in code, or the OutputTo action in macros.
For information about using the OutputTo method, see "Saving HTML Documents by Using the OutputTo Method" later in this
chapter.
How the Internet Database Connector Works
When you save a table, form, or query datasheet as Internet Connector
files, Microsoft Access creates two files: an Internet
Database Connector (IDC) file and HTML extension
(HTX) file. These files are used to generate a Web page
that displays current data from your database.
An IDC file contains the necessary information to connect to a
specified Open Database Connectivity (ODBC) data source and to
run an SQL statement that queries the database. The information
needed to connect to the database includes the data source name,
and if userlevel security is established for the database,
the user name and password required to open the database. For
example, if you save the Current Product List query datasheet
from the Northwind sample application as IDC/HTX files, Microsoft
Access creates the following IDC file:
An IDC file also contains the name and location of an HTML extension
(HTX) file. The HTX file is a template for the HTML document;
it contains field merge codes that indicate where the values returned
by the SQL statement should be inserted. For example, if you save
the Current Product List query datasheet from the Northwind sample
application as IDC/HTX files, Microsoft Access creates the following
HTX file:
Microsoft Access saves the HTX file to be used with an IDC file
with the same name as the IDC file, except with an .htx file name
extension rather than an .idc file name extension. After the database
information has been merged into the HTML document, it is returned
to the Web browser.
If you open Current Product List.idc from a Microsoft Internet
Information Server that has an appropriately defined Northwind
data source name (DSN), the Web page shown in the following illustration
is generated.
Note You
can also reference an HTML template when you create IDC and HTX
files. An HTML template contains additional HTML code to enhance
the appearance of the resulting pages. If you specify an HTML
template, it is merged with the HTX file. For information about
the format of an HTML template, see "Using an HTML Template When You Save Data as HTML Documents" earlier in this chapter.
Requirements for Using IDC/HTX Files
To use IDC/HTX files, your database and the IDC/HTX files must
reside on a computer running one of the following operating systems
and Internet server platforms:
Microsoft Internet Information Server, Microsoft Peer Web Services,
and Microsoft Personal Web Server use a component called the Internet
Database Connector (Httpodbc.dll) to generate dynamic Web pages
from IDC/HTX files.
The Internet Database Connector component requires ODBC drivers
to access a database. To access a Microsoft Access database, the
Microsoft Access Desktop driver (Odbcjt32.dll) must be installed
on your Web server. This driver is installed when you install
Microsoft Internet Information Server if you select the ODBC
Drivers And Administration check box during Setup.
However, the Microsoft Access Desktop driver isn't installed with
Microsoft Personal Web Server. If Microsoft Access is installed
on the computer you are using to run Microsoft Personal Web Server,
and if you selected the driver when you installed Microsoft Access,
the driver is already available. If you don't have Microsoft Access
installed on the computer you are using to run Microsoft Personal
Web Server, you must install the Microsoft Access Desktop driver.
To
install the Microsoft Access Desktop driver
If you are not running Setup for the first time, click
Add/Remove.
Important The
Microsoft Access check box must also be selected or the
driver will not be installed.
For information about how to define a system DSN or a file DSN,
search the Microsoft Access Help index for "ODBC, setting
up data sources." For more information about Microsoft Internet
Information Server, see the Microsoft Internet Information Server
Web site, located at http://www.microsoft.com/infoserv/iisinfo.htm.
For more information about using IDC/HTX files, search the Microsoft
Internet Information Server Help index for "database connector."
Tip You
can learn more about applications that use IDC/HTX files by reading
about the Job Forum application. For information about the Job
Forum application, see the Job Forum white paper, located at http://www.microsoft.com/accessdev/accwhite/jobforpa.htm.
For applications that require many users to access the database
simultaneously, you should consider upsizing the Microsoft Access
database backend server to Microsoft SQL Server. For information
about upsizing a Microsoft Access Web application to Microsoft
SQL Server, see http://www.microsoft.com/accessdev/accwhite/upsizeweb.htm.
Saving Forms and Datasheets as Active Server Pages
With Microsoft Access, you can save a form as an Active Server
Page (ASP) that emulates much of the functionality of your form.
When saving a form as an Active Server Page, Microsoft Access
saves most, but not all, controls on the form as ActiveX controls
that perform the same or similar functions. Microsoft Access doesn't
save or run Visual Basic code behind the form or controls. To
copy the layout of your form as closely as possible, Microsoft
Access uses the Microsoft HTML Layout control to position the
controls on Active Server Pages. The resulting page uses ActiveX
Scripting and ActiveX Data Objects to connect the control on the
page to a copy of your database on an Internet server. For information
about the Microsoft HTML Layout control, see http://www.microsoft.com/workshop/author/layout/layout.htm.
Users who open a form saved as an Active Server Page can browse
records, update or delete existing records, and add new records
by using a Web browser.
You can also save table, query, and form datasheets as Active
Server Pages. When you open a datasheet saved as an ASP, Microsoft
Access displays current data from a copy of your database located
on an Internet server, much like IDC/HTX files do. However, unlike
IDC/HTX files, Active Server Pages require only one file per datasheet.
The ASP file uses scripting to establish a connection to the database
on the server, and contains information that it uses to format
the datasheet. Unlike a form saved as an Active Server Page, users
can't update existing records in or add new records to a datasheet
saved as an Active Server Page.
To
save a form or datasheet as an Active Server Page
For information about HTML templates, see "Using
an HTML Template When You Save Data as HTML Documents" earlier
in this chapter.
You can also save forms and datasheets as Active Server Pages
by using the Publish to the Web Wizard (available through the
Save As HTML command on the File menu), the OutputTo
method in code, or the OutputTo action in macros. For information
about using the OutputTo method, see "Saving HTML Documents by Using the OutputTo Method" later in this chapter.
Form Views Supported for Active Server Pages
If the form you save as an Active Server Page has its DefaultView
property set to Single Form or Continuous Forms, the Active Server
Page displays as a single form, unless it is open in Datasheet
view when you use the Save As/Export command (File
menu). If the form has its DefaultView property set to
Datasheet, the Active Server Page displays as a datasheet. Subforms
always display as datasheets, regardless of their DefaultView
property setting. All field data types are saved unformatted,
that is, Format and InputMask property settings
aren't saved.
Control Types Supported for Active Server Pages
When Microsoft Access saves a form as an Active Server Page, it
replaces Microsoft Access controls with ActiveX controls, as described
in the following table.
Microsoft Access doesn't support the following controls when saving
a form as an Active Server Page:
Note You
can simulate a rectangle or a line by using a Label control without
a caption.
Requirements for Using Active Server Pages
To display and use an Active Server Page, a copy of your database
and Active Server Pages must reside on a computer running one
of the following operating systems and Internet server platforms:
The Microsoft HTML Layout control must be installed on the computer
opening the Active Server Page. For more information about installing
the Active Server Pages components for Peer Web Services and Personal
Web Server, see http://www.microsoft.com/ntserver/. Active Server
Pages also require the Microsoft Access Desktop driver and a valid
DSN to access a database. For information about installing the
Microsoft Access Desktop driver and defining DSNs, see "Requirements for Using IDC/HTX Files" earlier in this chapter.
Using the Publish to the Web Wizard
With the Publish to the Web Wizard, you can publish a set of Microsoft
Access database objects to any combination of static HTML documents,
IDC/HTX files, or Active Server Pages (ASP). By using the wizard,
you can:
To run the Publish to the Web Wizard, click Save As HTML
on the File menu. For more information about using the
Publish to the Web Wizard, search the Microsoft Access Help index
for "Saving database objects, saving in Internet/Web formats."
Saving HTML Documents by Using the OutputTo Method
You can use the OutputTo method to save Microsoft Access
database objects in the HTML formats described in the previous
sections: static HTML documents, IDC/HTX files, or Active Server
Pages (ASP).
The syntax of the OutputTo method is:
DoCmd.OutputTo objecttype, objectname,
outputformat, outputfile,
autostart, templatefile
The following table describes the arguments of the OutputTo
method.
acOutputForm
If you run Visual Basic code that contains the OutputTo method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.
acFormatHTML
You can include the standard file name extension (.asp, .htm, .html, or .htx,) for the output format you select with the outputformat argument, but it's not required. If you output to IDC/HTX or ASP files, Microsoft Access always creates files with the standard .htx and .idc or .asp file name extensions.
If you leave this argument blank, Microsoft Access prompts you for an output file name.
If you leave this argument blank, Microsoft Access uses the default value (False).
Microsoft Internet Information Server and Microsoft Active Server
Pages formats are available only for tables, queries, and forms,
so if you specify acFormatIIS or acFormatASP for
the outputformat argument, you must specify
acOutputTable, acOutputQuery, or acOutputForm
for the objecttype argument.
You can leave an optional argument blank in the middle of the
syntax, but you must include the argument's comma. If you leave
a trailing argument blank, don't use a comma following the last
argument you specify.
You can't specify the HTML template, data source name, user name
and password, server URL, or Session timeout setting when
you use the OutputTo method. Microsoft Access uses the
values specified on the Hyperlinks/HTML tab of the Options
dialog box (Tools menu) by default. However, you can use
the SetOption method in your code to temporarily change
these settings. For information about using the SetOption
method, search the Microsoft Access Help index for "SetOption
method."
Examples
The following example outputs the Employees table in static HTML
document format to the Employee.htm file and immediately opens
the file in the default Web browser.
The following example outputs the Employees table in IDC/HTX format
to two files named Employee.htx and Employee.idc. It merges the
Mc.htm template file into the Employee.htx file.
The following example outputs the Products form in Active Server
Page format to the Products.asp file. It merges the Stones.htm
template file into the Products.asp file.
Saving Microsoft Word Documents as HTML
Documents
You can save an existing Word document to HTML format by using
the Save As command (File menu) or by using Visual
Basic code. The following example saves the active document as
an HTML document.
When you save an existing Word document to HTML format, formatting
and other items that aren't supported by HTML or the Word Web
page authoring environment are removed from the file. For more
information about what happens when you save a Word document as
a Web page, search Word Help. Instead of saving existing documents
as HTML, you may want to create new HTML documents with Microsoft
Word Web authoring tools.
Word 97 has many powerful features for creating HTML documents,
such as the following:
Word Editing and Formatting Features Take
advantage of advanced Word editing and formatting features
richtext formatting, spelling and grammar checking, and
automatic text correction when you work with Word
Web authoring tools. When you use a Word Web template, you can
easily create and format popular Web page items
such as tables, bulleted or numbered lists, and graphic objects
just as you can with a regular Word document.
Word Web Templates Use the
Web Page Wizard or the Blank Web Page template to create new Web
pages. The Web Page Wizard gives you different layouts and color
themes to choose from, such as a personal home page, a table of
contents, a survey, or a registration form. To use the wizard
or the template, click New on the File menu, click
the Web Pages tab, and then doubleclick Web Page
Wizard or Blank Web Page. There are several additional
Web templates that you can download from the Microsoft Word Web
site at http://www.microsoft.com/word/. When you download these
templates, they are installed in the same folder as the existing
Web templates.
Hyperlinks, Bullets, and Horizontal Lines By
using the Insert Hyperlink button on the Standard
toolbar, you can quickly create hyperlinks on your Web page to
link related information in different locations. The hyperlink
text is usually blue and underlined. You can also quickly create
special graphical bulleted lists and horizontal lines for your
Web page. To add a new bullet for selected text, click Bullets
and Numbering on the Format menu, and then select the
bullet you want. To add the default bullet to selected text, click
Bullets on the Formatting toolbar. To add a new
horizontal line, click Horizontal Line on the Insert
menu, and then select the line style you want.
Forms You can use forms to
collect and present data on your Web page. For example, you can
publish a form that collects user feedback or registration information.
You can store the input data in a database or a text file for
future use. You can quickly create a form by selecting a sample
form and then modifying it for your needs by using the Forms
toolbar. To select a sample form, click New on the File
menu, click the Web Pages tab, and then select the sample
form you want. To display the Control Toolbox, click Form
Design Mode on the Standard toolbar. Use the Web form
tools just as you use the regular Word form tools to insert form
elements.
Saving Microsoft Excel Worksheets as HTML
Documents
To make your Microsoft Excel data available to users on your intranet
or the World Wide Web, use the Internet Assistant addin
program to convert worksheet data or charts to HTML Web pages
(Save As HTML command, File menu). Microsoft Excel
doesn't support using Visual Basic to save data as HTML documents.
Saving Microsoft PowerPoint Presentations
as HTML Documents
To make your Microsoft PowerPoint data available to users on your
intranet or the World Wide Web, use the Internet Assistant addin
program to convert presentations to HTML Web pages (Save As
HTML command, File menu). Microsoft PowerPoint doesn't
support using Visual Basic to save data as HTML documents.
Each Office application provides features that you can use to
open and import HTML data. You can also use Office applications
to open documents and files in a variety formats on your company's
intranet. If you have a connection to the Internet, you can open
or import data in most of these same formats on Internet sites
such as FTP and HTTP servers.
Note In
all Office applications except Outlook, you can use Data Access
Objects (DAO) code in Visual Basic to access and manipulate data
in a variety of formats, including HTML. For more information
about using DAO, see Chapter 11, "Data Access Objects."
Opening HTML Data in Microsoft Word
To open HTML documents in Microsoft Word with Visual Basic, use
the Open method. By default, the Open method tries
each available file converter until it succeeds. For this reason,
as long as the HTML Document converter is installed, the following
example opens an HTML document on a local drive.
Similarly, you can specify a URL to open a file located on an
HTTP server, as follows.
To improve performance, you can specify the file converter to
use by referring to it in the FileConverters collection,
as follows.
Opening HTML Data in Microsoft Excel
To open HTML documents in Microsoft Excel with Visual Basic, use
the Open method. You don't need to specify the file converter
to use, because the Open method tries each available file
converter until it succeeds. The following example opens an HTML
document on a local drive.
Similarly, you can specify a URL to open a file located on an
HTTP server, as follows.
Piece Description
Required? displaytext The text the user sees in the Hyperlink field in a table, or in a text box bound to the Hyperlink field. You can set the display text to any text string.
For example, you may want the display text to be a descriptive name for the Web site or object specified by the address and subaddress. If you do not specify display text, Microsoft Access displays the value of address, or subaddress if address is also not specified.
No address
A valid URL that points to a page or file on the Internet or an intranet, or the path to a file on a local hard disk or LAN.
If you enter a path on a LAN, you can omit a mapped drive letter and use the universal naming convention (UNC) format: \\server\share\path\filename. This prevents the path from becoming invalid if the database is later copied to another computer's hard disk or into a shared network folder.
Yes, unless subaddress points to an object in the current database (.mdb) file.
subaddress
The location within a file or document; for example, a database object, such as a form or report. When referring to a database object, the name of the object should be preceded by its type: Table, Query, Form, Report, Macro, or Module. Other possible values for subaddress include a bookmark in a Word document, a NAME anchor tag in an HTML document, a PowerPoint slide, or a cell in a Microsoft Excel worksheet.
No
Hyperlink field value
Goes to Cajun Delights#http://www. cajundelights.com/cajun.htm#
The Cajun Delights Web page. Only the words "Cajun Delights" are displayed in the field or control.
#http://www.cajundelights.com/cajun.htm#
The Cajun Delights Web page. The text "http://www.cajundelights.com" appears in the field or control because no display text is specified.
#http://www.cajundelights. com/cajun.htm#Price
The HTML anchor with the NAME attribute Price on the Cajun Delights Web page. The text "http://www.cajundelights. com/cajun.htm" is displayed.
Resume#c:\windows\personal\resume.doc#
A Microsoft Word file named Resume.doc located in the \Windows\Personal folder. Only the word "Resume" is displayed in the field or control.
#c:\windows\personal\resume.doc#
A Microsoft Word file named Resume.doc located in the \Windows\Personal folder. The text "c:\windows\personal\resume.doc" appears in the field or control because no display text is specified.
#c:\windows\personal\resume. doc#Qualifications
The section in the Resume.doc Word file marked with the bookmark name Qualifications. The text "c:\windows\personal\resume.doc" is displayed.
#\\databases\samples\northwind.mdb#Form Suppliers
The Suppliers form in the Northwind sample application located in the Samples share on the Databases server on a LAN (UNC format path). The text "\\databases\samples\northwind.mdb" is displayed.
Suppliers Form##Form Suppliers
The Suppliers form in the current database. The words "Suppliers Form" are displayed in the field or control.
#c:\windows\personal\1996 Sales.ppt#13
Slide 13 in the 1996 Sales PowerPoint presentation located in the \Windows\Personal folder. The text "c:\windows\personal\1996 Sales.ppt" is displayed.
#c:\windows\personal\budget.xls#Sheet1!A2
The A2 cell in Sheet1 of the Budget.xls file located in the \Windows\Personal folder. The text "c:\windows\personal\budget.xls" is displayed.
Argument Description
object Optional. The Application object.
hyperlink Required. A Variant that represents the data stored in a Hyperlink field.
part Optional. The value for the part argument is an intrinsic constant that represents the information you want returned by the HyperlinkPart function.
Constant Value
Description
acDisplayedValue
0 (Default) The underlined text displayed in a hyperlink.
acDisplayText
1 The displaytext part of a Hyperlink field.
acAddress
2 The address part of a Hyperlink field.
acSubAddress
3 The subaddress part of a Hyperlink field.
Hyperlink field data
HyperlinkPart function returned values
#http://www.microsoft.com/#
acDisplayedValue: http://www.microsoft.com/
acDisplayText: No value returned.
acAddress: http://www.microsoft.com/
acSubAddress: No value returned.
Microsoft#http://www.microsoft.com/#
acDisplayedValue: Microsoft
acDisplayText: Microsoft
acAddress: http://www.microsoft.com/
acSubAddress: No value returned.
Customers##Form Customers
acDisplayedValue: Customers
acDisplayText: Customers
acAddress: No value returned.
acSubAddress: Form Customers
##Form Customers acDisplayedValue: Form Customers
acDisplayText: No value returned.
acAddress: No value returned.
acSubAddress: Form Customers
DisplayHyperlinkParts "MyHyperlinkTableName", "MyHyperlinkFieldName"
Sub DisplayHyperlinkParts(strTable As String, strField As String)
Dim dbs As Database, rst As Recordset
Dim strMsg As String
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset(strTable)
While Not rst.EOF ' For each record in table.
strMsg = "DisplayValue = " & HyperlinkPart(rst(strField), acDisplayedValue) _
& vbCrLf & "DisplayText = " & HyperlinkPart(rst(strField), acDisplayText) _
& vbCrLf & "Address = " & HyperlinkPart(rst(strField), acAddress) _
& vbCrLf & "SubAddress = " & HyperlinkPart(rst(strField), acSubAddress)
' Show parts returned by HyperlinkPart function.
MsgBox strMsg
rst.MoveNext
Wend
End Sub
SELECT Links.URL, HyperlinkPart([URL],0)
AS Display, HyperlinkPart([URL],1)
AS Name, HyperlinkPart([URL],2)
AS Addr, HyperlinkPart([URL],3) AS SubAddr
FROM Links;
Private Sub Form_Current()
Dim txt As TextBox
On Error GoTo Error_Form1
' Set reference to the txtAddress text box bound to a Hyperlink field.
Set txt = txtAddress
' Follow the hyperlink.
txt.Hyperlink.Follow
Exit_Form1:
Exit Sub
Error_Form1:
MsgBox Err & ": " & Err.Description
Resume Exit_Form1
End Sub
Sub CreateHyperlinkField()
Dim db As Database
Dim tbl As TableDef
Set db = CurrentDb()
Set tbl = db.CreateTableDef("Hyperlinks")
With tbl
.Fields.Append .CreateField("Text", dbText)
.Fields.Append .CreateField("Hyperlink", dbMemo)
.Fields("Hyperlink").Attributes = dbHyperlinkField
End With
db.TableDefs.Append tbl
RefreshDatabaseWindow
End Sub
If
Anchor tag format
The hyperlink doesn't include a subaddress
<A HREF="address">displaytext</A>
The hyperlink includes a subaddress
<A HREF="address#subaddress">displaytext</A>
Display text isn't specified
<A HREF="address">address</A>
Placeholder Description
Location <!--AccessTemplate_Title-->
The name of the object being saved
Between <TITLE> and </TITLE>
<!--AccessTemplate_Body-->
The data or object being saved
Between <BODY> and </BODY>
<!--AccessTemplate_FirstPage-->
An anchor tag to the first page
Between <BODY> and </BODY> or after </BODY>
<!--AccessTemplate_PreviousPage-->
An anchor tag to the previous page
Between <BODY> and </BODY> or after </BODY>
<!--AccessTemplate_NextPage-->
An anchor tag to the next page
Between <BODY> and </BODY> or after </BODY>
<!--AccessTemplate_LastPage-->
An anchor tag to the last page
Between <BODY> and </BODY> or after </BODY>
<!--AccessTemplate_PageNumber-->
The current page number
Between <BODY> and </BODY> or after </BODY>
Datasource:Northwind
Template:Current Product List.htx
SQLStatement:SELECT [Product List].ProductID, [Product List].ProductName
+FROM Products AS [Product List]
+WHERE ((([Product List].Discontinued)=No))
+ORDER BY [Product List].ProductName;
Password:
Username:
<HTML>
<TITLE>Current Product List</TITLE>
<BODY>
<TABLE BORDER=1 BGCOLOR=#ffffff><FONT FACE="Arial" COLOR=#000000>
<CAPTION><B>Current Product List</B></CAPTION>
<THEAD>
<TR>
<TD><FONT SIZE=2 FACE="Arial" COLOR=#000000>Product ID</FONT></TD>
<TD><FONT SIZE=2 FACE="Arial" COLOR=#000000>Product Name</FONT></TD>
</TR>
</THEAD>
<TBODY>
<%BeginDetail%>
<TR VALIGN=TOP>
<TD ALIGN=RIGHT><FONT SIZE=2 ACE="Arial" COLOR=#000000><%ProductID%><BR></FONT></TD>
<TD><FONT SIZE=2 FACE="Arial" COLOR=#000000><%ProductName%><BR></FONT></TD>
</TR>
<%EndDetail%>
</TBODY>
<TFOOT></TFOOT>
</BODY>
</HTML>
After the Microsoft Access Desktop driver is installed, you must
create either a system DSN or a file DSN that specifies the name
and connection information for each database you want to use on
the server. You then specify that DSN when you generate the IDC/HTX
files.
Microsoft Access control ActiveX control
Text box Text box.
Text box control bound to a Hyperlink field
Text box that displays the hyperlink text, but the hyperlink can't be followed.
List box List box.
Combo box Combo box.
Label Label. If the label has HyperlinkAddress and/or HyperlinkSubAddress properties set, an HTML hyperlink is created for the label.
Command button Command button, but any code behind the button isn't saved. If the command button has HyperlinkAddress and/or HyperlinkSubAddress properties set, an HTML hyperlink is created for the button.
Option group Option group, but without a group frame.
Option button Option button.
Check box Check box.
Toggle button Toggle button.
ActiveX control ActiveX control, but any code behind the control isn't saved.
Subform Subform as datasheet only.
Argument Description
objecttype Required. Specifies the type of database object you are going to output. You can use one of the following constants for the objecttype argument:
acOutputQuery
acOutputReport
acOutputTableobjectname Optional. A string expression that's the valid name of an object of the type specified in the objecttype argument. If you want to output the active object, specify the object's type for the objecttype argument and leave this argument blank.
outputformat Optional. Specifies whether to save the database object as an HTML document, IDC/HTX file, or Active Server Page. You can use one of the following constants for the outputformat argument:
acFormatIIS
acFormatASP
If you leave this argument blank, Microsoft Access prompts you for the output format.outputfile Optional. A string expression that's the full name, including the path, of the file you want to output the object to.
autostart Optional. Use True ( 1) to start a Web browser immediately to open the static HTML document specified by the outputfile argument. Use False (0) if you don't want to start the application. This argument is ignored for IDC/HTX and ASP files.
templatefile Optional. A string expression that's the full name, including the path, of the file you want to use as a template for an HTML, IDC/HTX, or ASP file.
DoCmd.OutputTo acOutputTable, "Employees", acFormatHTML, "Employee.htm", True
DoCmd.OutputTo acOutputTable, "Employees", acFormatIIS, "Employee",, _
"C:\Program Files\Microsoft Office\Templates\Access\Mc.htm"
DoCmd.OutputTo acOutputFor
321m, "Products", acFormatASP, "Products",, _
"C:\Program Files\Microsoft Office\Templates\Access\Stones.htm"
Sub SaveAsHTML
Dim intFormat As Integer
intFormat = FileConverters("HTML").SaveFormat
myDocName = ActiveDocument.Name
pos = InStr(myDocName, ".")
If pos > 0 Then
myDocName = Left(myDocName, pos -1)
myDocName = myDocName & ".html"
ActiveDocument.SaveAs FileName:=myDocName, FileFormat:=intFormat
End If
End Sub
Documents.Open "C:\My Documents\My Document.htm"
Documents.Open "http://myserver.com/default.htm"
Sub OpenHTML()
Dim intFormat As Integer
intFormat = FileConverters("HTML").OpenFormat
Documents.Open "http://myserver.com/default.htm", Format:=intFormat
End Sub
Workbooks.Open "C:\My Documents\Product List.htm"
Workbooks.Open "http://myserver.com/default.htm"
You can also get data from an intranet site or from HTTP, FTP, or Gopher sites on the World Wide Web by running a Web query. To run a Web query, point to Get External Data on the Data menu, and then click Run Web Query. For more information about running Web queries, see http://www.microsoft.com/excel/webquery/.
Opening HTML Data in Microsoft PowerPoint
To open HTML documents in PowerPoint with Visual Basic, use the
Open method. By default, the Open method tries each
available file converter until it succeeds. For this reason, as
long as the HTML Document converter is installed, the following
line of code will open an HTML document on a local drive:
Presentations.Open "C:\My Documents\My Document.htm"
Similarly, you can specify a URL to open a file located on an HTTP server:
Presentations.Open "http://myserver.com/default.htm"
Importing HTML Data in Microsoft Access
With Microsoft Access, you can import or link data from HTML tables
or other data sources on an Internet server. For more information
about importing, exporting, and linking HTML data and other data
formats on Internet servers, see "Working with HTML Files"
in Chapter 18 and "Importing, Linking, and Exporting
Data on the Internet" in Chapter 21 in Building
Applications with Microsoft Access 97.
The Microsoft WebBrowser control is an ActiveX control that you
can use to browse Web sites, view Web pages and other documents,
and download data located on the Internet from your applications.
The WebBrowser control is useful in situations where you don't
want to disrupt the work flow in your application by switching
to a Web browser or other documentviewing application.
The WebBrowser control can display any Web page that Microsoft
Internet Explorer version 3.0 can display. For example, the WebBrowser
control can display pages that include any of the following features:
With the WebBrowser control, users of your application can browse
sites on the World Wide Web, as well as folders on a local hard
disk and on a local area network. Users can follow hyperlinks
by clicking them or by typing a URL into a text box. Also, the
WebBrowser control maintains a history list that users can browse
through to view previously browsed sites, folders, and documents.
In addition to opening Web pages, both Microsoft Internet Explorer
version 3.0 and the WebBrowser control can open any ActiveX document,
which includes most Office documents. For example, if Office is
installed on a user's computer, an application that uses the WebBrowser
control can open and edit Microsoft Excel workbooks, Word documents,
and PowerPoint presentations from within the control. Similarly,
if Microsoft Excel Viewer, Word Viewer, or PowerPoint Viewer is
installed, users can open those documents within the WebBrowser
control, but they cannot edit them.
You can't open and edit a Microsoft Access database as an ActiveX
document within Microsoft Internet Explorer version 3.0 or the
WebBrowser control, but a Web page can contain a hyperlink to
a Microsoft Access database. Clicking the hyperlink downloads
a copy of the database and starts a session of Microsoft Access
to open it. Additionally, if you have the server software that
supports Internet Database Connector/HTML extension (IDC/HTX)
files or Active Server Pages (ASP), you can create Web pages that
act as a frontend to an ODBC data source such as a Microsoft
Access or Microsoft SQL Server database. For more information
about creating IDC/HTX or ASP files, see "Saving Microsoft Access Data as HTML Documents" earlier in this chapter.
Adding the WebBrowser Control to a Form
Before you can use the WebBrowser control, you must have Microsoft
Internet Explorer version 3.0 or later installed.
If you purchased Microsoft Office 97 on CDROM, you
can install Microsoft Internet Explorer version 3.0 by running
Msie30.exe from the Iexplore subfolder in the ValuPack folder.
If you prefer to install from the Web, you can download and install
Microsoft Internet Explorer version 3.0 from http://www.microsoft.com/ie/download/.
Once you have Microsoft Internet Explorer version 3.0 installed,
the WebBrowser control is automatically registered and is available
in form Design view (Microsoft Access) and in Design mode (Microsoft
Excel, Word, and PowerPoint).
To
add the WebBrowser control to a document or form
A menu appears that lists all the registered ActiveX
controls in your system.
In Microsoft Excel, Word, and PowerPoint, you can also add the
WebBrowser control to UserForms created with the Visual Basic
editor.
To
add the WebBrowser control to a UserForm created with the Visual
Basic Editor
This starts the Visual Basic Editor or switches to
its window if it's already open.
A blank form is created and the toolbox is displayed.
The Additional Controls dialog box is displayed.
A tool icon is added to the toolbox for the WebBrowser
Control. You don't need to repeat steps 4 and 5 the next time
you use the toolbox.
For more information about UserForms, see Chapter 12, "ActiveX Controls and Dialog Boxes."
Tip If
the WebBrowser control can't display the full width or height
of a Web page or document, it automatically displays scroll bars.
However, in most cases, make the control wide enough to display
the full width of a typical Web page so that users of your application
don't have to scroll horizontally.
Displaying Web Pages or Documents in the
WebBrowser Control
To display a Web page or document in the WebBrowser control, use
the Navigate method in Visual Basic. The syntax for the
Navigate method is:
object.Navigate URL
Object is either the name of the WebBrowser
control on your form or an object variable that refers to it,
and URL is a string expression that evaluates
to a valid URL or path. URL can refer to a
Web page or other content on the Internet or an intranet, as well
as to an Office document, such as a Word document.
If URL refers to an Internet protocol and a
location on the Internet, the WebBrowser control must establish
a connection before is can display the document. If the computer
running your application is connected to a proxy server
(a secure connection to the Internet through a LAN), or if it
has a direct connection to the Internet, the WebBrowser control
downloads and displays the Web page or other Internet content
immediately. If the computer running your application uses a modem
and dialup connection to the Internet, and that connection
hasn't been established beforehand, the WebBrowser control initiates
the connection. For example, if the user's computer uses a modem
and The Microsoft Network to connect to the Internet, the Sign
In dialog box is displayed to establish the connection to
the Internet before the WebBrowser control can display Internet
content.
If URL refers to an Internet protocol and a
location on an intranet server, the computer running your application
must be connected to the intranet and have permission to access
that server.
If URL refers to a standard file system path
on a local hard disk or LAN, the WebBrowser control opens the
document and displays it immediately. The WebBrowser control can
open Office documents (except Microsoft Access databases), text
files, and HTML documents that don't require features supported
only by an Internet/intranet server. For example, the WebBrowser
control can't open and run IDC/HTX files or ASP files from the
standard file system, but it can open HTML documents that contain
only the HTML tags supported by Microsoft Internet Explorer version
3.0.
Note If
URL refers to a path in the standard file system that doesn't
refer to a file name (for example, C:\Windows\System\), the WebBrowser
control displays the file system itself, much like My Computer.
The examples and code in the following sections are specific to
developing an application that uses the WebBrowser control in
Microsoft Access; however, in most cases, you can apply the same
basic principles and techniques to using the WebBrowser control
in applications developed with other Office applications.
Displaying a Document in the WebBrowser Control by Using an
Address in a Text Box
By using the WebBrowser control, you can create a Microsoft Access
form that performs most of the functions of Microsoft Internet
Explorer version 3.0. For example, the following illustration
shows the Custom Browse form (WebBrowseWeb) in the Developer Solutions
sample application.
When a user types a valid URL in the text box at the top of the
form (txtLinks)
and presses ENTER, the WebBrowser control
(ActiveXCtl1)
displays the Web page or document. Pressing ENTER
triggers the AfterUpdate event of the txtLinks
text box; the AfterUpdate event contains the following code, which
goes to the address specified in the URL that the user entered.
Error handling is passed to the control itself because it displays
the same error messages displayed by Microsoft Internet Explorer
version 3.0.
If you prefer to start navigation by clicking a command button
instead pressing ENTER, you can use similar
code in the button's Click event.
The Home, Back, Forward, Refresh, and Search buttons on the Custom
Browse form use the corresponding GoHome, GoBack,
GoForward, Refresh, and GoSearch methods
of the WebBrowser control. For information about how to view brief
descriptions about the properties, methods, and events of the
WebBrowser control, see "Viewing Descriptions of the Properties, Methods, and Events of the WebBrowser Control" later in this
chapter.
With the Save Location button on the Custom Browse form, you can
save the address and a description of the current document to
the Links table in the Developer Solutions sample application.
When you click the Save Location button, Microsoft Access checks
to see if the URL has been saved previously, and if not, uses
the following statement to open the Save Location To Table
dialog box.
The last argument of this statement (ctlHyper.LocationName
& ";" & ctlHyper.LocationURL)
sets the OpenArgs property to a concatenated string that
contains the two values returned by the LocationName and
LocationURL properties of the document currently displayed
in the Custom Browse form. When the Save Location To Table
dialog box opens, code in its Load event parses the OpenArgs
property value back into two parts and displays them as the default
description and address. When the user clicks OK, the description
and address in the Save Location To Table dialog box form
are saved in the Hyperlink and Description fields in the Links
table.
For more information about the Custom Browse form, open the Developer
Solutions sample application located in the Samples subfolder
of your Office folder. To view the Developer Solutions sample
application, you must click Custom when you install Microsoft
Access and then choose to install all sample databases.
Displaying a Document in the WebBrowser Control by Using a
Hyperlink Stored in a Table
By using the WebBrowser control, you can create a Microsoft Access
form that displays documents specified in hyperlinks stored in
a table. For example, the following illustration shows the Browse
Saved Hyperlinks form (WebBrowseTable) in the Developer Solutions
sample application. You can use the Browse Saved Hyperlinks form
to browse addresses saved in the Links table.
When a user clicks a record navigation button at the bottom of
the form to move to a new record, the following code in the form's
Current event displays the Web page or document whose address
is stored in the current record.
This procedure uses the Navigate method of the WebBrowser
control to display the next hyperlink address. However, don't
pass the contents of a Hyperlink field directly to the Navigate
method. If a user enters or edits data stored in a Hyperlink field
from a datasheet or form, it may contain up to three parts of
information separated by the pound sign (#). Even if the user
doesn't enter all three parts in the datasheet or form, Microsoft
Access automatically stores pound signs in the field. If there
are pound signs in the Hyperlink field, passing the data from
the field directly to the Navigate method generates an
error. To handle this, the stored value is passed to the HyperlinkPart
function to extract just the address portion
of the saved hyperlink, which is then passed to the Navigate
method. If navigation is successful, the form's Bookmark
property value is stored in a public variable. This public variable
is used to return to the last record if subsequent navigation
fails.
Using code to save data in a Hyperlink field doesn't automatically
save pound signs in the field. To preserve the proper functioning
of a Hyperlink field in other contexts, you may want to write
your code to save pound signs before and after a hyperlink address.
To see an example of how to do this, view the event procedure
set for the Click event of the Save Location button (cmdSaveLocation)
on the Custom Browse form.
Note You
don't have to store addresses in a Hyperlink field if you don't
need users to be able to navigate to addresses by clicking them
in datasheets or forms, or if you don't need to save addresses
as HTML anchor tags when saving as HTML. As long as an address
doesn't exceed 255 characters, you can store it in a Text field.
If an address exceeds 255 characters, you can store it in a Memo
field. In either case, you can pass the value stored in the field
directly to the Navigate method.
For more information about the Browse Saved Hyperlinks form, open
the Developer Solutions sample application located in the Samples
subfolder of your Office folder. For more information about the
format of data stored in a Hyperlink field, see "The Hyperlink Field Storage Format" earlier in this chapter.
Viewing Descriptions of the Properties,
Methods, and Events of the WebBrowser Control
Like builtin Office objects, the WebBrowser control has
properties that your application can set or read to determine
the control's characteristics, methods that your application can
use to perform operations on the control, and events your application
can respond to. You can view brief descriptions of the properties,
methods, and events of the WebBrowser control by using the Object
Browser.
Important In
order for these properties, methods, and events to appear in the
Object Browser, a reference must be set to the Microsoft Internet
Controls object library. To set this reference, open a module
(Microsoft Access) or open the Visual Basic Editor (Microsoft
Excel, Word, or PowerPoint), click References on the Tools menu,
and select the Microsoft Internet Controls check box in the Available
References box.
To
view descriptions of the WebBrowser control's methods, properties,
and events
The Members Of box lists the methods, properties, and events associated with the WebBrowser control.
For more information about the methods, properties, and events
of the WebBrowser control, see http://www.microsoft.com/intdev/sdk/docs/iexplore/.
If you purchased Microsoft Office 97 on CDROM, you
can open a Help file named Iexplore.hlp that contains this information
in the \ValuPack\Access\WebHelp folder on the CDROM.
Distributing the WebBrowser Control with
Your Application
Unlike most other ActiveX controls, you can't install the WebBrowser
control by itself. For an application that uses the WebBrowser
control to work, Microsoft Internet Explorer version 3.0 must
also be installed on the computer. Microsoft Internet Explorer
version 3.0 can be distributed freely, and doesn't require the
payment of royalties or other licensing fees. For information
about installing Microsoft Internet Explorer version 3.0, see
"Adding the WebBrowser Control to a Form" earlier in
this chapter.
Microsoft Office 97, Developer Edition provides the Internet
Transfer control (Msinet.ocx), which you can use to connect to
and retrieve files from any Web site that uses either Hypertext
Transfer Protocol (HTTP) or File Transfer Protocol (FTP). For
example, you could use the Internet Transfer control to:
Because HTTP and FTP work differently, the operations you can
perform with the Internet Transfer control depend on which protocol
you are using. For example, the GetHeader method only works
with HTTP (HTML documents). However, there are a few operations
that you can perform with either protocol:
Tip The
Internet Transfer control automatically sets itself to the correct
protocol, as determined by the protocol portion
of the URL. Therefore, when you use the OpenURL or Execute
method, you don't need set the Protocol property.
Adding the Internet Transfer Control to
a Form
In Microsoft Excel, Word, and PowerPoint, you can add the Internet
Transfer control to a UserForm you create with the Visual Basic
Editor. Although the Internet Transfer control is available in
the toolbox in Microsoft Excel, Word, and PowerPoint, you
can't add the control directly to their documents. In Microsoft
Access, you can add the Internet Transfer control to a form in
Design view. The Internet Transfer control doesn't display when
your application is running.
To
add the Internet Transfer control to a Microsoft Excel, Word,
or PowerPoint UserForm created with the Visual Basic Editor
This starts the Visual Basic Editor or switches to
its window if it's already open.
A blank form is created and the toolbox is displayed.
The Additional Controls dialog box is displayed.
A tool icon is added to the toolbox for the Internet
Transfer control. You don't need to repeat steps 4 and 5 the next
time you use the toolbox.
By default, the new control is named Inetn, where
n is some number.
To
add the Internet Transfer control to a Microsoft Access form
A menu appears that lists all the registered ActiveX
controls in your system.
By default, the new control is named ActiveXctln,
where n is some number.
Setting the AccessType Property
In order to make any kind of connection to the Internet, you must
determine how your computer is connected to the Internet. If you
are on an intranet you will probably be connected to the Internet
through a proxy server.
When using a proxy server, all computers on an intranet that need
to connect to the Internet must do so through the proxy server.
By using a proxy server, sometimes called a firewall,
you can protect your local area network from being accessed by
others on the Internet. The proxy server acts as a oneway
barrier between your internal network and the Internet, preventing
others on the Internet from accessing confidential information
on your internal network.
To determine the proxy server settings on your computer
Note The following steps apply only to computers running Windows 95
and Windows NT Workstation version 4.0.
If you want to use a proxy server other than that named in the
Proxy Settings dialog box, set the AccessType property
of the Internet Transfer control to icNamedProxy (2).
Then set the Proxy property to the name of the proxy server
you want to use.
If you prefer to use the default proxy server, set the AccessType
property to icUseDefault (0). You don't need to set the
Proxy property when you use the default proxy server.
The following table describes the settings for the AccessType
property.
Using the OpenURL Method
After you have set the AccessType property, the most basic
operation is to use the OpenURL method with a valid URL
to retrieve data on the Internet. When you use the OpenURL
method, the result depends on the target URL. The following example
returns the HTML document found on the Microsoft home page at
http://www.microsoft.com to a text box named Text1.
In Microsoft Access, a value assigned to the Text property
can't be longer than 1,024 characters. Substitute the following
line of code that sets the Value property of the text box
instead.
As a result, the text box displays the HTML source code from the
Web site, which may resemble the following illustration.
In this case, the default action was to return the HTML document
located at the URL. However, if the URL specifies a particular
text file, the OpenURL method retrieves the actual file.
For example, the following code:
retrieves the actual text of the file, as shown in the following
illustration.
Finally, you can use the OpenURL method with a URL that
includes extra data appended to it. For example, many Web sites
offer the ability to search a database. To search a database from
a Web site, you can send a URL that includes the search criteria.
The following example uses the search engine at the www.yahoo.com
site with the search criteria p=maui.
If the search engine finds a match for the criteria, the server
returns an HTML document that contains the appropriate information.
Saving Text to a File by Using the OpenURL Method
If you want to save retrieved text to a file, use the OpenURL
method with the Open, Write, and Close statements,
as shown in the following example.
You can't save binary files to disk by using the OpenURL
method. You must use the Execute method in conjunction
with the GetChunk method as described later in this chapter.
Synchronous vs. Asynchronous Transmission
The OpenURL method results in a synchronous
transmission of data. In this context, synchronous means that
the transfer operation occurs before any other procedures are
run. Thus the data transfer must be completed before you can run
any other code.
The Execute method, on the other hand, results in an asynchronous
transmission. When you use the Execute method,
the transfer operation occurs independently of other procedures.
Thus, after the Execute method is initiated, other code
can run while data is received in the background.
Using the OpenURL method results in a direct stream of
data that you can save to disk, or view directly in a TextBox
control (if the data was text). On the other hand, if you
are using the Execute method to retrieve data, you must
monitor the control's connection state by using the StateChanged
event. When the appropriate state is reached, use the GetChunk
method to retrieve data from the control's buffer. This operation
is discussed in greater detail in the sections that follow.
Using the Execute Method
You can use the Execute method with the FTP and the HTTP
protocols to retrieve data or perform operations on Internet servers.
The syntax for the Execute method is:
controlname.Execute url,
operation, data, requestheaders
The following table describes the arguments of the Execute
method.
Using the Execute Method with the FTP Protocol
When using the Execute method with the FTP protocol, you
only use the operation argument, and optionally,
the url argument. The url argument
is optional because after the first time you invoke the Execute
method with the url argument, the FTP connection
remains open. You can perform additional Execute method
operations on the same URL until a new URL is specified, or until
you perform the CLOSE operation. The following example retrieves
a file from a remote computer.
For FTP operations, you do not use the data
and requestheaders arguments. You pass all
of the operations and their parameters as a single string in the
operation argument, with parameters separated
by a space, as follows:
operationname parameter1 parameter2
For example, to retrieve a file, the following code includes the
operation name (GET), and the two file names required by the operation.
The operationname part of the operation
argument is an FTP command. If you have used
FTP to retrieve files from anonymous FTP servers, you are familiar
with commands used to navigate through server trees, and to retrieve
files to a local hard disk. For example, to change to a different
directory with the FTP protocol, you use the "CD"
command with the path to the directory you want to change to.
For the most common operations, such as putting a file on a server
and retrieving a file from a server, the Internet Transfer control
uses the same or a similar command with the Execute method.
The following example uses the "CD"
command as an argument of the Execute method to change
to a different directory.
The following table lists the FTP commands that you can use in
the operation argument of the Execute
method.
Important If
your proxy server is a CERN proxy server, you cannot make direct
FTP connections by using the Execute method. In that case, to
get a file, use the OpenURL method with the Open, Put, and Close
statements, as described in "Saving Text to a File by Using
the OpenURL Method" earlier in this chapter. You can also
use the OpenURL method to get a directory listing by invoking
the method and specifying the target directory as the URL.
Logging On to FTP Servers
FTP servers can be either public or private. Anyone can log on
to a public server. To log on to a private server, on the other
hand, you must be a registered user of the server. In either case,
the FTP protocol requires that you supply a user name and a password.
When logging on to public servers, it is common practice to log
on as "anonymous," (UserName = "anonymous")
and use your email name as the password. With the Internet
Transfer control, the process of logging on is simplified even
further. By default, if you do not specify values for the UserName
and Password properties, the Internet Transfer control
uses "anonymous" as your user name, and your email
name as the password.
If you are logging on to a private server, set the UserName,
Password, and URL properties to appropriate values,
and use the Execute method, as shown in the following example.
After you invoke the Execute method, the FTP connection
remains open. You can then continue to use the Execute
method to perform other FTP operations such as CD and GET. When
you have completed the session, close the connection by using
the Execute method with the CLOSE operation. You can also
close the connection automatically by changing the URL
property, and invoking either the OpenURL or Execute
method; this closes the current FTP connection and opens the new
URL.
Using the Execute Method with the HTTP Protocol
When you use the Execute method with the HTTP protocol
to request data from the server, you use the GET, HEAD, POST,
and PUT methods in the operation argument.
You can use these methods with the Execute method, as shown
in the following table.
Using the Execute Method with the Common Gateway Interface
On many World Wide Web sites, you can search a database for criteria
that you specify. Most Web sites accomplish this by using the
HTTP protocol, which can send queries that use the Common Gateway
Interface (CGI).
It is not in the scope of this section to explain the CGI; however,
if you are familiar with the CGI, you can use the Execute
method to construct an application that simulates the search behavior
of these Web sites. The following example shows a typical CGI
query string.
You could send this same query by using the Execute method,
as follows.
Private Sub txtLinks_AfterUpdate()
On Error Resume Next
' If the user has entered an address (URL) in this control,
' attempt to go to the address.
If Len(Me!txtLinks) > 0 Then
Me!ActiveXCtl1.Navigate Me!txtLinks
End If
End Sub
DoCmd.OpenForm "frmSaveURLDialog", acWindowNormal, , , acFormEdit, acDialog, _
ctlHyper.LocationName & ";" & ctlHyper.LocationURL
Private Sub Form_Current()
Dim varFull As Variant, varDescription As Variant
Dim HyperlinkAddress As String, HyperlinkSubAddress As String
Dim msg1 As String, msg2 As String, rst As Recordset, strDisplay As String
On Error Resume Next
Set rst = Me.RecordsetClone
rst.Bookmark = Me.Bookmark
varFull = rst!HyperLink
If IsNull(varFull) Then GoTo Current_Err
varDescription = rst!Description
Me!ActiveXCtl1.Navigate HyperlinkPart(varFull, acAddress)
If Err = 438 Then Exit Sub
gvarBookMark = Me.Bookmark
Current_Bye:
Exit Sub
Current_Err:
msg1 = "Invalid hyperlink address. Remove the record described as '"
msg2 = "' from the Links table or edit the hyperlink to supply a valid address."
MsgBox msg1 & rst!Description & msg2
Me.Bookmark = gvarBookMark
Exit Sub
End Sub
Constant Value
Description
icUseDefault
0 (Default) The control uses default proxy server settings found in the Windows registry.
IcDirect
1 The control has a direct connection to the Internet.
IcNamedProxy
2 The control uses the proxy server specified in the Proxy property.
' A TextBox control named Text1 contains the
' return result of the method. The Internet Transfer
' control is named Inet1.
Text1.Text = Inet1.OpenURL("http://www.microsoft.com/")
Text1.Value = ActiveXCtl0.OpenURL("http://www.microsoft.com/")
' In Microsoft Access, substitute Text1.Value
' for Text1.Text in the following line.
Text1.Text = Inet1. OpenURL("ftp://ftp.microsoft.com/disclaimer.txt")
Dim strURL As String
strURL = "http://www.yahoo.com/bin/search.exe?p=maui"
' In Microsoft Access, substitute Text1.Value
' for Text1.Text in the following line.
Text1.Text = Inet1.OpenURL(strURL)
Dim strURL As String
Dim intFile As Integer
IntFile = FreeFile()
strURL = "http://www.microsoft.com/"
Open "MSsource.txt" For Output As #IntFile
Write #IntFile, Inet1.OpenURL(strURL)
Close #IntFile
Argument Description
controlname Required. The name of the Internet Transfer control you are working with.
url Optional. Specifies the URL that you want to connect to.
operation Optional. Specifies the type of operation to perform.
data Optional. Specifies additional information needed for HTTP GET, HEAD, POST, and PUT methods.
requestheaders Optional. Specifies additional headers to be sent from the remote server.
Inet1.Execute "FTP://ftp.microsoft.com", _
"GET disclaimer.txt c:\temp\disclaimer.txt"
' Get the file named Disclaimer.txt and copy it to the
' location C:\Temp\Disclaimer.txt.
Inet1.Execute, "GET Disclaimer.txt C:\Temp\Disclaimer.txt"
' The txtURL text box contains the path to open. The txtRemotePath
' text box contains the path to change to.
Inet1.Execute txtURL.Text, "CD " & txtRemotePath.Text
FTP command
Description Example
CD path
Change Directory. Changes to the directory specified in path.
Inet1.Execute , "CD docs\mydocs"
CDUP Changes to parent directory. Same as "CD .."
Inet1.Execute , "CDUP"
CLOSE Closes the current FTP connection.
Inet.Execute , "CLOSE"
DELETE file
Deletes the file specified in file.
Inet1.Execute , _
"DELETE discard.txt"
DIR path
Searches the directory specified in path. If path isn't supplied, the current working directory is searched. Use the GetChunk method to return the directory listing.
Inet1.Execute , "DIR /mydocs"
GETfile1 file2
Retrieves the remote file specified in file1, and creates a new local file specified in file2.
Inet1.Execute , _
"GET getme.txt C:\gotme.txt"
MKDIR path
Creates a directory as specified in path. Success is dependent on user privileges on the remote host.
Inet1.Execute , "MKDIR /myDir"
PUT file1 file2
Copies a local file specified in file1to the remote host specified in file2.
Inet1.Execute , _
"PUT C:\putme.txt /putme.txt"
PWD Print Working Directory. Returns the current directory name. Use the GetChunk method to return the directory name.
Inet1.Execute , "PWD"
QUIT Terminate current connection
Inet1.Execute , "QUIT"
RECV file1 file2
Same as GET.
Inet1.Execute , _
"RECV getme.txt C:\gotme.txt"
RENAME file1 file2
Renames a file. Success is dependent on user privileges on the remote host.
Inet1.Execute , _
"RENAME old.txt new.txt
RMDIR path
Removes a directory. Success is dependent on user privileges on the remote host.
Inet1.Execute , "RMDIR oldDir"
SEND file
Copies a file to the remote host. (same as PUT.)
Inet1.Execute , _
"SEND C:\putme.txt /putme.txt"
SIZE file
Returns the size of the file specified in file.
Inet1.Execute _
"SIZE /largefile.txt"
With Inet1
.URL = "ftp://ftp.someFTPSite.com"
.UserName = "John Smith"
.Password = "mAuI&9$6"
.Execute ,"DIR" ' Returns the directory.
.Execute ,"CLOSE" ' Close the connection.
End With
HTTP method
Description Example
GET Retrieves the file specified in the url argument.
Inet1.Execute _
"http://www.microsoft.com" & _
"/default.htm", "GET"
HEAD Retrieves only the headers of the file specified in the url argument.
Inet1.Execute , "HEAD"
POST Provides additional data to support a request to the remote host.
Inet1.Execute , "POST", strFormData
PUT Replaces data at the specified URL.
Inet1.Execute , "PUT", "replace.htm"
http://www.yippee.com/cgi-bin/find.exe?find=Hangzhou
Dim strURL As String, strFormData As String
strURL = "//www.yippee.com/cgi-bin/find.exe"
strFormData = "find=Hangzhou"
Inet1.Execute strURL, "POST", strFormData
To retrieve resulting data from a server, you must use the GetChunk method, as described in the following section.
Using the GetChunk Method
When you download data from a remote computer by using the Execute
method, an asynchronous connection is made. For example, if you
use the Execute method with the HTTP GET method, the server
retrieves the requested file. When the entire file has been retrieved,
the StateChanged event returns icResponseCompleted (12).
At that point, you can use the GetChunk method to retrieve
the data from the buffer. This is shown in the following example.
Private Sub Inet1_StateChanged(ByVal State As Integer)
Dim vtData As Variant ' Data variable.
Dim intFile As Integer ' File number variable.
intFile = FreeFile() ' Get free file number.
Select Case State
.
. ' Other cases not shown.
.
Case icResponseCompleted
' Open a file to write to.
Open "test.txt" For Binary Access _
Write As #intFile
' Get the first chunk. NOTE: specify a byte
' array (icByteArray) to retrieve a binary file.
vtData = Inet1.GetChunk(1024, icString)
Do While LenB(vtData) > 0
Put #intFile, , vtData
' Get next chunk.
vtData = Inet1.GetChunk(1024, icString)
Loop
Put #intFile, , vtData
Close #intFile
End Select
End Sub
Microsoft Office 97, Developer Edition also provides the WinSock control, which you can use to connect to a remote computer and exchange data. You use the WinSock control with either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP). You can use both protocols to create client and server applications. The WinSock control doesn't have a visible interface at run time.
You can use the WinSock control to:
Determining Which Protocol to Use
To use the WinSock control, you must first decide which protocol
to use. The major difference between TCP and UDP is their connection
state:
Here are a few questions that may help you determine which protocol
to use:
Adding the Control to a Form
In Microsoft Excel, Word, and PowerPoint, you can add the WinSock
control to a UserForm you create with the Visual Basic Editor.
Although the WinSock control is available in the Control Toolbox
in Microsoft Excel, Word, and PowerPoint, you can't add the control
directly to their documents. In Microsoft Access, you can add
the WinSock control to a form in Design view. The WinSock control
doesn't display when your application is running.
To
add the WinSock control to a Microsoft Excel, Word, or PowerPoint
UserForm created with the Visual Basic Editor
This starts the Visual Basic Editor or switches to
its window if it's already open.
A blank form is created and the toolbox is displayed.
The Additional Controls dialog box is displayed.
A tool icon is added to the toolbox for the WinSock
control. You don't need to repeat steps 4 and 5 the next time
you use the toolbox.
By default, the new control is named Winsockn, where
n is some number.
To
add the WinSock control to a Microsoft Access form
A menu appears that lists all the registered ActiveX
controls in your system.
By default, the new control is named ActiveXctln,
where n is some number.
Setting the Protocol Property
After you add the WinSock control to your form, you specify which
protocol you are going to use. If you want to use the UDP protocol,
set the Protocol property to sckUDPProtocol. The
default setting of the Protocol property is sckTCPProtocol.
You can set the Protocol property in the property sheet
or in Visual Basic code, as follows.
Determining the Name of a Computer
To connect to a remote computer, you must know either its Internet
Protocol (IP) address or its "friendly name." The IP
address is a series of three digit numbers separated by periods
(nnn.nnn.nnn.nnn).
It's much easier to remember the friendly name of a computer.
To
determine the name of a computer
After you have determined a computer's name, you can use it as
the value for the RemoteHost property of a WinSock control,
as shown in the examples later in this section.
Creating an Application That Uses the
TCP Protocol
When creating an application that uses the TCP protocol, you must
first decide if your application will be a client or a server.
The client makes a connection request, which the server can then
accept to complete the connection. After the connection is complete,
the client and server can freely communicate with each other.
To
create a TCP server
These procedures create a simple server application. To complete
the scenario, you must also create a client application.
To
create a TCP client
The preceding code creates a simple client/server application.
To try the two together, make a copy of the application and put
it on another computer. Open the client on one computer and open
the server on the other computer. Then click Connect on
the client form. When you type text into the txtSendData text
box on either form, the same text appears in the txtOutput text
box on the other form.
Accepting More Than One Connection Request
With Microsoft Word, Microsoft Excel, Microsoft PowerPoint, and
Microsoft Access forms, you can only create a server that accepts
only one connection request. However, you can use Microsoft Visual
Basic version 4.0 or later to create a server application that
accepts several connection requests by using the same control.
To do so, you create a new instance of the control by setting
its Index property; this creates a control array. Then
you invoke the Accept method on the new instance. You do
not need to close the connection.
The following code assumes there is a WinSock control on a form
named sckServer, and that its Index property has been set
to 0; thus the control is part of a control array. In the Declarations
section, a modulelevel variable intMax is declared. In the
form's Load event, intMax is set to 0, and the LocalPort
property for the first control in the array is set to 1001. Then
the Listen method is invoked for the control, making it
the control that receives connection requests. As each connection
request arrives, the code tests it to see if the Index
property is 0 (the value of the "listening" control).
If so, the listening control increments intMax, and uses that
number to create a new control instance. The new control instance
then accepts the connection request.
Creating an Application That Uses the
UDP Protocol
Creating a UDP application is even simpler than creating a TCP
application because the UDP protocol doesn't require a connection.
After you create the forms, add the WinSock controls, and set
the Protocol property to UDPProtocol, you add code on both
computers that performs the following steps:
The Bind method reserves a local port for use by the WinSock
control. For example, when you bind the control to port number
1001, no other application can use that port to receive connection
requests. This may be useful if you want to prevent another application
from using that port.
If there is more than one network adapter on the machine, you
can specify which adapter to use in the LocalIP
argument the Bind method. If you do not specify which network
adapter to use, the control uses the first adapter listed in the
Network dialog box, which is available through the computer's
Control Panel.
When using the UDP protocol, you can change the setting of the
RemoteHost and RemotePort properties while remaining
bound to the same local port. However, with the TCP protocol,
you must close the connection before changing the RemoteHost
and RemotePort properties.
In the TCP application created in the previous section, you must
set the WinSock control on the client to receive connection requests,
and the WinSock control on the server must initiate a connection.
In contrast, the two computers in a UDP application do not have
such restrictive roles. Both computers can send and receive messages.
Because both computers can be considered equal in the relationship,
a UDP application is sometimes called a peertopeer
application.
The following procedures create a UDP application that two people
can use to exchange messages in real time, or "talk"
to each other.
To
create a UDP Peer
To
create a second UDP Peer
To try this example, make a copy of the application and put it
on another computer. Open the first peer on one computer and open
the second peer on the other computer. When you type text into
the txtSendData text box on either form, the same text appears
in the txtOutput text box on the other form.
Winsock1.Protocol = sckUDPProtocol
Private Sub Form_Load()
' Set the LocalPort property to an integer.
' Then invoke the Listen method.
tcpServer.LocalPort = 1001
tcpServer.Listen
End Sub
Private Sub tcpServer_ConnectionRequest
(ByVal requestID As Long)
' Check if the value of the control's State property
' is closed. If not, close the connection before
' accepting the new connection.
If tcpServer.State <> sckClosed Then tcpServer.Close
' Accept the request with the requestID parameter.
tcpServer.Accept requestID
End Sub
Private Sub txtSendData_Change()
' The TextBox control named txtSendData
' contains the data to be sent. Whenever the user
' types into the textbox, the string is sent
' using the SendData method.
tcpServer.SendData txtSendData.Text
End Sub
Private Sub tcpServer_DataArrival (ByVal bytesTotal As Long)
' Declare a variable for the incoming data.
' Use the GetData method and set the Text
' property of a TextBox named txtOutput to
' the data.
Dim strData As String
tcpServer.GetData strData
' In Microsoft Access, substitute txtOutput.Value
' for txtOutput.Text in the following line.
txtOutput.Text = strData
End Sub
Important Set
the value of the RemoteHost property to the name of your computer.
Private Sub Form_Load()
' The name of the Winsock control is tcpClient.
' Note: To specify a remote host, you can use
' either the IP address (ex: "121.111.1.1") or
' the computer's friendly name, as shown here.
tcpClient.RemoteHost = "RemoteComputerName"
tcpClient.RemotePort = 1001
End Sub
Private Sub cmdConnect_Click()
' Invoke the Connect method to initiate a
' connection.
tcpClient.Connect
End Sub
Private Sub txtSendData_Change()
tcpClient.SendData txtSendData.Text
End Sub
Private Sub tcpClient_DataArrival _
(ByVal bytesTotal As Long)
Dim strData As String
tcpClient.GetData strData
' In Microsoft Access, substitute txtOutput.Value
' for txtOutput.Text in the following line.
txtOutput.Text = strData
End Sub
Private intMax As Long
Private Sub Form_Load()
intMax = 0
sckServer(0).LocalPort = 1001
sckServer(0).Listen
End Sub
Private Sub sckServer_ConnectionRequest _
(Index As Integer, ByVal requestID As Long)
If Index = 0 Then
intMax = intMax + 1
Load sckServer(intMax)
sckServer(intMax).LocalPort = 0
sckServer(intMax).Accept requestID
Load txtData(intMax)
End If
End Sub
Private Sub Form_Load()
' The control's name is udpPeerA.
With udpPeerA
.Protocol = sckUDPProtocol ' Set the control to UDP protocol.
.RemoteHost= "PeerB" ' Set RemoteHost property to the
'name of the other computer.
.RemotePort = 1001 ' Port to connect to.
.Bind 1002 ' Bind to the local port.
End With
frmPeerB.Show
' Show second form.
End Sub
Private Sub txtSendData_Change()
' Send text as soon as it's typed.
udpPeerA.SendData txtSendData.Text
End Sub
Private Sub udpPeerA_DataArrival
(ByVal bytesTotal As Long)
Dim strData As String
udpPeerA.GetData strData
' In Microsoft Access, substitute txtOutput.Value
' for txtOutput.Text in the following line.
txtOutput.Text = strData
End Sub
Private Sub Form_Load()
' The control's name is udpPeerB.
With udpPeerB
.Protocol = sckUDPProtocol ' Set the control to UDP protocol.
.RemoteHost= "PeerA" ' Set RemoteHost property to the
'name of the other computer.
.RemotePort = 1002 ' Port to connect to.
.Bind 1001 ' Bind to the local port.
End With
End Sub
Private Sub txtSendData_Change()
' Send text as soon as it's typed.
udpPeerB.SendData txtSendData.Text
End Sub
Private Sub udpPeerB_DataArrival (ByVal bytesTotal As Long)
Dim strData As String
udpPeerB.GetData strData
' In Microsoft Access, substitute txtOutput.Value
' for txtOutput.Text in the following line.
txtOutput.Text = strData
End Sub
Microsoft provides two products that make it easy to create a personal Web server on your computer for lowvolume Web publishing: Microsoft Personal Web Server and Microsoft Peer Web Services. These products are ideal for publishing departmental home pages, personal home pages, or smallscale Web applications on your company's intranet.
Although Personal Web Server and Peer Web Services are intended for smallscale Web publishing, they provide most of the same services and features as Microsoft Internet Information Server, a robust Web server intended for highvolume Web publishing. You can use Personal Web Server or Peer Web Services to develop and test Web applications, and then transfer them to a Web server running Microsoft Internet Information Server.
Both Personal Web Server and Peer Web Services can:
Installation Requirements
To run Personal Web Server or Peer Web Services, you must meet
the following installation requirements.
Personal Web Server
Peer Web Services
Publication Requirements
When using Personal Web Server or Peer Web Services, each computer
you want to access the server must have Transmission Control Protocol/Internet
Protocol (TCP/IP) installed. The TCP/IP protocol is included with
Windows 95 and Windows NT Workstation version 4.0. To
install and configure the TCP/IP protocol and related components,
doubleclick the Network icon in Control Panel. Each
system must meet additional requirements depending on whether
you want to use the server on an intranet or the Internet.
Intranet Publication Requirements
Internet Publication Requirements
Installing Personal Web Server |
The Setup file for Personal Web Server is available on the Web. To download the Setup program for Personal Web Server for Windows 95, connect to the Microsoft Personal Web home page at:
http://www.microsoft.com/ie/iesk/pws.htm
You can install Personal Web Server if you are running Windows 95 or Windows NT Workstation version 4.0. However, if you are using Windows NT, it is recommended that you install Peer Web Services instead.
To install Personal Web Server from the Value Pack
This starts the installation process. You may be required to supply additional files from your Windows 95 Setup disks.
Installing Peer Web Services
The files to install Peer Web Services are provided on the Microsoft
Windows NT Workstation version 4.0 Setup CDROM.
To
install Peer Web Services
This starts the installation process. You may be required
to supply additional files from your Windows NT Setup disks.
Getting More Information
For more information about Using Personal Web Server or Peer Web
Services, you can refer to their online documentation, which is
available once installation is complete.
To
view documentation for Personal Web Server or Peer Web Services
http://MyServer/docs/default.htm
To view the documentation for Peer Web Services, in
your browser's address box, type:
http://MyServer/iisadmin/htmldocs/inetdocs.htm
where MyServer is the name of the computer on which
you installed Personal Web Server or Peer Web Services. To determine
the name of the computer, open Control Panel, doubleclick
the Network icon, and then click the Identification tab.