Catégorie : Excel VBA Course

  • What is a Conditional Hyperlink

    To make a hyperlink enabled or disabled depending on a certain condition, use it together with the IF() function. For example:

    =IF(C1="May",HYPERLINK("[D:\Sales.xlsx]May!A1","Sales"),""

    Automatic changes of a hyperlink depending on the value in a cell can easily be implemented using the IF() or CHOOSE() function. For example, do the following:

    • Create and save on drive D: the following Microsoft Excel workbooks: May.xlsx, June.xlsx, July.xlsx.
    • Open a new workbook and enter the following formula in cell A1:
    =CHOOSE(1, HYPERLINK("D:\May.xlsx","May"), HYPERLINK("D:\June.xlsx","June"), HYPERLINK("D:\July.xlsx","July"))
    • Make sure that cell A1 displays the hyperlink May. When you click it, the corresponding file located on drive D: will open.
    • By changing the index (the first argument) in the CHOOSE() function to 2 or 3, check the transition to the hyperlinks for the files June.xlsx or July.xlsx, respectively.

     

  • How to Create a Hyperlink with a Worksheet Formula with Excel VBA

    A hyperlink can also be created using the worksheet function HYPERLINK():

    HYPERLINK(link_location, [friendly_name])
    • link_location — the path and file name of the document to be opened. The address can refer to a place within a document, for example, a specific cell or a named range in an MS Excel workbook, or a bookmark in an MS Word document. The path may be a file path on a hard disk, a UNC server address (in MS Excel for Windows), or a URL address on the Internet or intranet.
    • friendly_name — the text to display for the link or a numeric value shown in the cell. The name appears in blue and underlined. If this argument is omitted, the cell displays the link_location as the link text.

    NOTE
    The arguments of the HYPERLINK() function can be either text expressions or cell references.

    For example, if in the workbook Department.xlsx you need to go from cell B3 to cell A20 of the worksheet Report (cell B3 may itself be on the Report sheet, so movement is possible both within one sheet and between sheets), then you would enter the following hyperlink in cell B3:

    =HYPERLINK("[Department.xlsx]Report!A20","Go to report")

    or the formula:

    =HYPERLINK(A1,B1)

    where cell A1 contains [Department.xlsx]Report!A20, and cell B1 contains Go to report.

    The first of the following two hyperlinks opens the workbook Sales.xlsx located in the root directory of drive D:, while the second opens the workbook and activates the worksheet May:

    =HYPERLINK("D:\Sales.xlsx","Sales")
    =HYPERLINK("[D:\Sales.xlsx]May!A1","Sales")

    A hyperlink to the Russian-language Microsoft webpage can be created as follows:

    =HYPERLINK("http://www.microsoft.com/ru/ru/","Microsoft")
  • How to Add Hyperlinks to MS Office Documents

    When working with a Microsoft Excel workbook, you often need to use documents prepared in various MS Office applications. For example, by adding hyperlinks to worksheets, you can move between these documents with a single mouse click.

    To create a hyperlink to another MS Office document (including the current workbook, but to a different cell range or another worksheet) in an MS Excel worksheet:

    • Select the range or shape to which the hyperlink will be attached.
    • Go to the Insert tab on the ribbon and, in the Links group, click the Hyperlink button.
    • In the Insert Hyperlink window, set the necessary options. The switches File, Web Page, Place in This Document, Create New Document, Email Address in the Link to group specify the document that the hyperlink will point to. The Text to Display field specifies the hyperlink text. In the Look in field, choose the folder that contains the desired document. From the lists Current Folder, Browsed Pages, and Recent Files, you can select the required file. In the Address drop-down list, you can specify the document’s URL. The ScreenTip button allows you to add text to the hyperlink’s tooltip, and the Bookmark button lets you choose a specific location to which the hyperlink will jump.
    • After setting the required parameters, click OK.

    You can edit a hyperlink by right-clicking on it. A context menu will appear with three commands for working with hyperlinks:

    • Edit Hyperlink — opens the Edit Hyperlink window, where you can change the path to the linked file and its name, as well as add an explanatory note to the hyperlink;
    • Open Hyperlink — opens the linked document, just as if you clicked the hyperlink;
    • Remove Hyperlink — deletes the hyperlink.
  • What You Need to Know About the Internet with Excel VBA

    The convenient interface of the World Wide Web (WWW) links the vast number of resources available on the Internet. Using the WWW, you can move among thousands of computer nodes, system applications, files, and documents. The ease of moving between documents and the ability to read them on any computer system has enabled organizations to adopt web technology. Many corporations and enterprises develop their own networks based on Internet technologies (intranets) to host internal information intended only for employees.

    Thus, when accessing resources located on other computers, we are dealing with resources of a computer network. A computer network is two or more computers connected by a shared data transmission channel. By territorial and organizational characteristics, computer networks are divided into:

    • Local Area Networks (LANs) — cover an organization, a group of organizations, or a district and use a single high-speed data transmission channel;
    • Wide Area Networks (WANs) — operate worldwide and use all possible communication channels (including, for example, satellite links).

    A local network is usually called an intranet, whereas the global world-wide network is called the Internet. As a rule, the architectural principle for building networks is the client–server model.

    Today, the Internet is a virtual space consisting of software, networks of various tiers, computers, and terminals (for data input and display) that is constantly growing and being updated to meet the new needs of modern society. The many local computer networks that make up the Internet are interconnected by high-speed communication channels at the continental level.

    Given the enormous number of networks that form the Internet, to get to the right place you need to know the address formats in use. The numbers used to identify a computer on the Internet are called IP addresses. Every computer on the Internet has a unique IP address consisting of a combination of four groups of digits, each not exceeding 255 in decimal notation. Because an IP address is not very convenient for users, every computer on the Internet also has a DNS address (Domain Name Service), for example, www.domainname.org. Such a name is called a domain name.

    To access a particular type of resource available on the Internet—for example, to view information published on a page—you must enter the address of that page on the Internet. This address is called a Uniform Resource Locator (URL). Depending on how the document must be accessed (through a local disk, a local network, a web site, or a file archive), the URL may look different (even for the same document). A URL consists of two parts: a protocol specifier for accessing the given resource and a location specifier for the resource itself. For example:

    • file://c:\sales\sales.htm — a file on the local computer;
    • file://brig\sales\sales.htm — a file on a computer in the local network;
    • http://brig/sales/sales.htm — a file on a web server in an intranet;
    • http://brig.boreas.ru/sales/sales.htm — a file on a remote web server on the Internet;
    • ftp://brig.boreas.ru/sales/sales.htm — a file on a remote FTP server on the Internet.

    If a specific file is not indicated in the URL, the web page configured as the default for that web server opens.

    The term “web server” (web site) can be interpreted in several ways. On the one hand, it is a set of documents connected by hyperlinks (in this case the web server has a main page from which all other pages are reachable in one or more steps). On the other hand, the term “web server” can mean the computer on which this set of documents is hosted and made accessible over a local or global network. Finally, the term may also refer to the software intended to provide access to the set of documents over a local or global network. Throughout this chapter, unless noted otherwise, we mean the first definition of “web server.”

    A web page (or Internet page, or HTML document) is a text file that contains special document markup commands. If you open a web page in a plain text editor (for example, Notepad), you will see exactly these commands. However, when opened with a web browser such as Internet Explorer, Mosaic, or Netscape, the web page can display text, graphics, hyperlinks to other documents, and also controls. The secret is that a web browser contains an interpreter of HTML commands embedded in the web page file.

    HTML (Hypertext Markup Language) is a document markup system for subsequent publication on the World Wide Web. Documents prepared in HTML format include images and links as well as formatting commands. To view these documents, a web browser (for example, Microsoft Internet Explorer) is used.

    A hyperlink is text highlighted in blue or underlined (or otherwise styled as defined by the user), or a graphical image. Clicking a hyperlink navigates to a file, to a specific location within a file, to an HTML page on the World Wide Web, or to an HTML page in an intranet. Hyperlinks can also point, for example, to a terminal emulation protocol (Telnet), to newsgroups, or to FTP sites. As you move between pages via hyperlinks, a browsing history of all pages is created and stored. Web browsers such as Internet Explorer have navigation buttons on their toolbars that allow you to move forward or back from one viewed page to another.

    Publishing is the process of outputting tables, forms, and reports in static or dynamic HTML format and then deploying all related files as World Wide Web applications to a web server, for example, Microsoft Internet Information Server or Microsoft Personal Web Server.

    To view information published on the Internet, special programs called browsers (web browsers) are used. Browsers provide users with access to information, convenient tools for viewing it, and tools for creating their own web pages.

    One well-known browser used as a convenient and reliable means of navigating Internet resources is Microsoft Internet Explorer.

    With Internet Explorer you can not only view web pages, but also work with Microsoft Office Word documents, Excel worksheets, and PowerPoint presentations regardless of whether the document was saved as a web page or in the application’s standard format. When opening documents saved in the standard format of the application that created them, the corresponding application’s menus and toolbars appear inside Internet Explorer, allowing you to edit the document directly in Internet Explorer. This has become possible thanks to ActiveX technology.

    Main Internet Services

    • WWW (World Wide Web) — a tool for working with hypertexts, allowing the retrieval and storage of different types of information (text, graphics, video, audio, etc.); hypertext documents are hosted on web servers that are part of the Internet.
    • FTP (File Transfer Protocol) — a method of transferring files between computers in the network regardless of their types, operating systems, file systems, or file formats.
    • E-mail (Electronic Mail) — a means of sending and receiving electronic messages between network users.
    • Usenet (newsgroups) — a service for distributing electronic messages among network users (one message is sent to a large group of users for public discussion).
    • IRC (Internet Relay Chat) — a service for real-time direct communication on the Internet among many users.
    • ICQ (I seek you) — an interactive communication service for users of the World Wide Web, which does not require a permanent IP address.

    A user of this service registers on the central server www.icq.com and receives a personal identification number — UIN (Universal Internet Number) — which can always be used to establish contact with other users of the network who are also using this interactive communication service.

    Microsoft Office and the Internet

    Microsoft Office integrates two powerful information technologies that define the model of working with a computer.

    • The first is based on the ability to store information anywhere — on a local hard disk, in a local or corporate network, or on the Internet.
    • The second is based on the principle that users actually work not with applications but directly with documents and the information contained in them.

    As a result, one of two possible approaches to working can be chosen:

    • Working mainly with Microsoft Office applications, with occasional access to the intranet or the Internet for a needed web page, a document, an add-in for an application, or additional information about a program.
    • Working mainly within the Internet Explorer browser, using it as the single environment in which you can view and edit any document located on your hard drive, in the company’s network, or on the Internet.

     

  • How to Perform Import and Export with Excel VBA

    If you want to perform import or export using VBA, you need to use the corresponding method.

    To import XML data into an Excel workbook , use the XmlImport method:

    expression.XmlImport(Url, ImportMap, Overwrite, Destination)

    • expression — a reference to the object (the workbook).
    • Url — a URL or full path to the file with XML data.
    • ImportMap — the map used when importing the file; if the data was imported earlier, this contains a reference to the object that stores the XML map.
    • Overwrite — determines whether to overwrite data that has been mapped by the map specified in the ImportMap parameter; set True to overwrite existing mapped data, set False to append new data to existing data; by default this parameter is True.
    • Destination — specifies the range where the imported data will be placed; this parameter holds a reference to the top-left cell of the range.

    Importing an XML file

    Sub Imp()
        ActiveWorkbook.XmlImport _
            URL:="D:\Data.xml", _
            ImportMap:=Nothing, _
            Overwrite:=True, _
            Destination:=Range("$A$1")
    End Sub

    To export data from an Excel workbook that contains a map, use the Export method of an XML map (the text refers to ExportXml, but the example shows exporting via an XmlMap object’s Export):

    expression.ExportXml(Data)

    • expression — a reference to the object (the workbook) that contains the XML map.
    • Data — the full path to the file to be exported.

    Exporting data to an XML file

    Sub Exp()
        ActiveWorkbook.XmlMaps("employees_map").Export _
            URL:="D:\Export.xml"
    End Sub
  • How to Export Data from Excel to an XML Document with Excel VBA

    Exporting data from an Excel worksheet to an XML document is similar to importing, but the steps are performed in reverse.
    It is also important to remember that exporting data to an XML document is not possible without the corresponding XML schema.

    So, perform the following steps:

    • Open the Microsoft Excel file that also contains an XML map (see file 8-File for export.xlsx on the CD).
    • Go to the Developer tab on the ribbon and in the XML group select the Export command.
    • In the Export XML dialog box that appears, choose the location for the exported data and, in the File name field, enter a name for the XML file to be saved. Click the Export button.
    • Make sure that the XML file you created uses UTF-8 encoding for Russian characters and that it can be viewed in a browser.

  • How to Import XML Data into Excel with Excel VBA

    If an XML document contains an XML schema, then when importing data from such a document, Excel can use the information from the schema linked to the XML document and store it in XML maps of the corresponding workbook into which the data from the original document is imported.
    When the original document does not contain a schema, Excel attempts to create an XML map on its own — based on an analysis of the data contained in the source document.

    Importing Data from an XML File Without an XML Schema

    To import data from an XML file:

    • Go to the File tab on the ribbon and choose Open.
    • In the Open File dialog box, click the drop-down list for All Excel Files and choose XML Files (*.xml). After this, only files of this type will be displayed in the file list area.
    • Select the required file in the file list area and click Open.
    • In the Open XML dialog box that appears, select the XML Table option and click OK.

    • If the file being opened does not contain a data schema, a warning will appear stating that Excel will create a schema based on the XML file.

    • Click OK — the data from the XML file will be imported onto an Excel worksheet.

    • To view the XML map created by Excel, go to the Developer tab on the ribbon and in the XML group click Source: in the task pane on the right side, the XML Source pane will open with the created XML map.

    Creating an XML Map and Importing Data from an XML File

    Suppose we already have an XML schema. To create an XML map in MS Excel, perform the following steps:

    • Open an Excel file (or create a new one) into which you need to import data from the XML document.
    • Go to the Developer tab on the ribbon and in the XML group click Source: in the task pane on the right side, the XML Source pane will open.

    • Click the XML Maps button in the lower-right corner of the XML Source pane — the XML Maps dialog box will open.
    • In the XML Maps dialog box, click Add to open the Select XML Source dialog box.

    • Select the file to create the map from and click Open.
    • If the selected source contains multiple root nodes, a dialog box for selecting a root node for the XML map will appear.
    • Choose the appropriate option from the list and click OK. A line with the parameters of the added map will appear in the XML Maps dialog box.

    • Highlight the name of the added schema in the XML Maps dialog box and click OK. The map will be added to the workbook and displayed in the XML Source pane in Excel’s working area.

    To use the added XML map:

    • Drag the required elements from the XML Source pane onto the worksheet to specify which fields to display on the worksheet.

    • Go to the Developer tab on the ribbon, in the XML group click Import. Then, after specifying the required file, the data will be imported into the Excel worksheet.

  • Why Are XML Schemas Needed with Excel VBA

    As mentioned earlier, when working with XML documents, a data schema describing their structure is necessary.
    In practice, the prolog usually contains an XML schema describing which elements the document using this schema may contain, which attributes correspond to which elements, and so on.

    If we draw an analogy with a database, an XML schema resembles the description of attributes and data types for tables in a database.
    A special language exists for describing schemas — XSD (XML Schema Definition Language).

    The process of comparing the contents of an XML document against a certain XML schema is called validation.

    The schema itself may be placed directly inside the document, but more often it is stored in a separate file with the .xsd extension, while the XML document itself contains a reference to this file.

    NOTE: A schema may be completely absent from the document — neither inside it nor as a reference. In this case, validation is carried out either manually or programmatically.

    Namespaces

    Several schemas can be used in a single XML document. In this case, the problem of name conflicts arises: different schemas may define the same names, and if a document refers to two such schemas, each defining the same element name differently, the question arises: which definition applies?

    To solve this problem, the concept of a namespace is introduced. By specifying a name, one can always determine the corresponding namespace. A namespace must also have a unique name (prefix). To specify a prefix, a URL (Uniform Resource Locator) can be used.

    A namespace is defined inside the opening tag of an element:

    <namespacePrefix:elementName xmlns:namespacePrefix = "URL">

    The URL used does not necessarily have to point to a real file, since its main purpose is to ensure uniqueness.

    A document may use several namespaces, one of which may remain unnamed. In this case, it is called the default namespace.

    Using a Default Namespace

    <?xml version="1.0" encoding="Windows-1251" ?>
    <!-- Using a default namespace -->
    <employee xmlns = "http://www.myorg.ru/staff">
      <name> Петров </name>
      <salary currency="р."> 100000 </salary>
    </employee>

    Requirements for an XML Schema

    Note that a schema is also an XML document and must satisfy the following requirements:

    • all schemas must have a top-level element named schema;
    • all schemas must use the same base namespace, whose URL is:
      http://www.w3.org/2001/XMLSchema.
      In addition to the base namespace, additional namespaces may also be used in the schema.

    For example, an XML schema with the base namespace bn can be defined as shown:

    Example of an XML Schema

    <?xml version="1.0" encoding="Windows-1251" ?>
    <bn:schema xmlns:bn="http://www.w3.org/2001/XMLSchema">
      <bn:element name="employee">
        <bn:complexType>
          <bn:sequence>
            <bn:element name="name" type="bn:string"/>
            <bn:element name="salary" type="bn:integer"/>
          </bn:sequence>
        </bn:complexType>
      </bn:element>
    </bn:schema>

    Schema Embedded in an XML Document

    The XML schema given in Listing 10.6 can be directly inserted into an XML document (Listing 10.7).

    Example of Using a Schema Inside an XML Document

    <?xml version="1.0" encoding="Windows-1251" ?>
    <employees>
      <!-- Beginning of schema -->
      <bn:schema xmlns:bn="http://www.w3.org/2001/XMLSchema">
        <bn:element name="employee">
          <bn:complexType>
            <bn:sequence>
              <bn:element name="name" type="bn:string"/>
              <bn:element name="salary" type="bn:integer"/>
            </bn:sequence>
          </bn:complexType>
        </bn:element>
      </bn:schema>
      <!-- End of schema -->
      <employee>
        <name> Петров </name>
        <salary>10000</salary>
      </employee>
      <employee>
        <name> Сидоров </name>
        <salary>15000</salary>
      </employee>
    </employees>

    External XML Schema

    In the previous section, we considered using a schema inside an XML document.
    However, the most optimal approach is to use an external schema stored in a separate file.

    Enter the code from Listing 10.6 in a text editor (e.g., Notepad) and save it under the name 5-Schema.xsd.

    To specify in the document that it should be validated using the schema stored in 5-Schema.xsd, it is necessary to reference this file in a special attribute (from the namespace http://www.w3.org/2001/XMLSchema-instance).

    • If the document refers to any additional namespaces (besides the one above), the schemaLocation attribute is used.
    • Otherwise, the noNamespaceSchemaLocation attribute is applied.

    XML Document Referring to Schema 5-Schema.xsd

    <?xml version="1.0" encoding="Windows-1251" ?>
    <!-- Using an external XML schema -->
    <employee xmlns:bni="http://www.w3.org/2001/XMLSchema-instance"
              bni:schemaLocation="employee 5-Schema.xsd">
      <name> Петров </name>
      <salary>10000</salary>
    </employee>

    Another Example of an XML Schema

    Let us now consider another XML schema, to be saved as 6-Schema.xsd, which allows the use of a list of multiple records.
    The corresponding XML document for this schema is shown:

    Example of an XML Schema for Verifying a List of Multiple Records

    <?xml version="1.0" encoding="Windows-1251" ?>
    <bn:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <bn:element name="employees">
        <bn:complexType>
          <bn:sequence>
            <bn:element ref="employee" maxOccurs="unbounded"/>
          </bn:sequence>
        </bn:complexType>
      </bn:element>
      <bn:element name="employee">
        <bn:complexType>
          <bn:sequence>
            <bn:element name="firstname" type="bn:string"/>
            <bn:element name="lastname" type="bn:string"/>
            <bn:element name="salary" type="bn:integer"/>
          </bn:sequence>
        </bn:complexType>
      </bn:element>
    </bn:schema>

    XML Document with a List of Multiple Employees

    <?xml version="1.0" encoding="Windows-1251" ?>
    <!-- Example of using an XML schema -->
    <employees xmlns:bni="http://www.w3.org/2001/XMLSchema-instance">
      bni:schemaLocation="employee 6-Schema.xsd"
      <employee>
        <firstname> Иван </firstname>
        <lastname> Петров </lastname>
        <salary> 10000 </salary>
      </employee>
      <employee>
        <firstname> Дмитрий </firstname>
        <lastname> Федоров </lastname>
        <salary> 9000 </salary>
      </employee>
      <employee>
        <firstname> Анна </firstname>
        <lastname> Котова </lastname>
        <salary> 15000 </salary>
      </employee>
    </employees>

     

  • Structure of an XML Document with Excel VBA

    An XML document consists of a prolog and a root element that includes all other elements.
    The prolog contains information about the version of XML used in the document and, as a rule, information about character encoding.
    Often, the prolog also contains information about the declaration of a standalone document and whether there are references to an external markup file, which may directly affect the editable XML file.

    Thus, the value « yes » in the standalone document declaration indicates the absence of external markup declarations that would affect the information passed by the XML processor to the application. For example, a prolog with a standalone document declaration looks like this:

    <?xml version="1.0" encoding="Windows-1251" standalone="yes"?>

    Accordingly, the simplest XML document may look like the one shown :

    Example of a simple XML document

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <!-- Example of an XML document -->
    <employee>
      <person lastname="Walkenbach" firstname="John"
              email="johnw@yandex.com"/>
      <person lastname="Wiley" firstname="Gary"
              email="gwiley@yandex.com"/>
    </employee>

    As a rule, XML code can be typed in a text editor and saved with the .xml extension. For example can be typed in Notepad and then opened in Internet Explorer.

    It should be noted that an XML document opened in a browser can be viewed element by element.
    For example, if you click the minus sign to the left of the <employee> element, the nested elements will be hidden.

  • Main Components of an XML Document with Excel VBA

    Similar to an HTML document, an XML document also contains tags.
    The main components of an XML document are elements, attributes, and comments.

    Elements are used to mark up parts (sections) of an XML document and have the following syntax:

    <Element> Content </Element>

    Here <Element> is the start tag, </Element> is the end tag, and Content is the value of the element.
    For example:

    <name> Walkenbach </name>

    The content refers to character data, while the elements belong to the markup of the document. In turn, character data is divided into Parsed Character Data (PCDATA) and Unparsed Character Data.

    Elements may have no content. For example:

    <cellphone></cellphone>

    In this case, they can be combined into one tag:

    <cellphone/>

    Elements may also be nested inside other elements:

    <employee>
      <name> Walkenbach </name>
      <salary> 10000 </salary>
    </employee>

    Attributes can be assigned to elements to provide additional information and to shorten the code.
    An attribute is a name=value pair placed inside the opening tag.
    For example, currency is an attribute of the <salary> tag:

    <salary currency="USD"> 10000 </salary>

    Or the <person> element could be written using attributes as follows.

    Using attributes in XML code

    <employee>
      <person lastname="Garnaev" firstname="Andrej" email="garnaev@yandex.ru"/>
      <person lastname="Rudikova" firstname="Lada" email="rudikowa@gmail.com"/>
    </employee>

    In addition, attributes allow elements to be divided into categories.
    For example, in the following code (Listing 10.2, see also file 1-Example.xml on the CD), depending on the value of the type attribute in the <person> element, the information is either confidential or public.

    Categorizing elements using attributes

    <?xml version="1.0" standalone="yes" ?>
    <employee>
      <person type="work">
        <lastname>Bond</lastname>
        <firstname>James</firstname>
        <email>bond007@yandex.com</email>
      </person>
      <person type="work">
        <lastname>Cooper</lastname>
        <firstname>Gary</firstname>
        <email>gcooper@yandex.com</email>
      </person>
      <person type="personal">
        <lastname>Cooper</lastname>
        <firstname>Gary</firstname>
        <marriedstatus>new married</marriedstatus>
        <homephone>354-56-56</homephone>
      </person>
    </employee>

    Comments in XML are written as follows:

    <!-- Example of a comment -->