What is external data in excel

Using Business Connectivity Services you can connect external data to your SharePoint site and use it as if it’s native to your site. Here is a collection of information about what external data is, where to get it, and how to use it.

Overview of external data

For more information, see Find content about external data.

In this article

  • Understand the big picture

    • Why use external data?

    • Three essential scenarios

    • Getting there is half the fun

    • Which hat do you wear?

  • Laying the groundwork

    • Know your SharePoint environment

    • Get the right software

    • Setup the software correctly

    • Choose your external data wisely

    • Consider performance

    • Practice safety first

    • Set the cornerstone: external content types

  • Surface external data in SharePoint products

    • Read and write data in external lists

    • Add external data columns to lists and libraries

    • Create solutions with Business Data Web Parts

    • Use external data in a profile page, action, or search

    • Use external data in workflows

  • Surface external data in Office products

    • Analyze external data in Excel

    • Add external data to Word documents

    • Synchronize external data in Outlook

    • Enhance external data access with InfoPath forms

    • Add external data to published Visio diagrams

    • Import and refresh external data in Access

Understand the big picture

There are many reasons to use external data. And a small team can do big things when it works together to create a business solution based on external data. Here’s how it’s often done and the rewards it can yield.

Why use external data?

As you use SharePoint products to help streamline your business activities, you may need to incorporate external data, such as databases, Line-of-Business applications, and Web services. But this external data is often like a secluded island that is restricted to privileged folks, or just plain hard to get to. Is there a way to get this external data smoothly into SharePoint products, as well as Office products, so that you can leverage a familiar interface and further enhance your business?

That’s what Business Connectivity Services is all about. It enables secure, efficient, read/write access to a wide variety of external data. This is done through a comprehensive framework that provides standard user and programming interfaces. Furthermore, you can create a wide range of business solutions, both no-code, SharePoint Composite solutions for simple to intermediate activities and code-based solutions for advanced needs. For example, you can:

  • Create a SharePoint external list of employee personnel data stored in a back-end database that users can read and write, similar to a native SharePoint list.

  • Connect up-to-date customer data in your organization’s Enterprise Resource Planning (ERP) system as a set of Outlook contacts and even provide offline access.

  • Create an event planning solution that links to a controlled Line-of-Business application, but uses a SharePoint calendar for all to see.

  • Create a Microsoft Silverlight application with a cool visual user interface that works with external data from the Web.

In short, Business Connectivity Services lets you connect to, interact with, and unlock the value of external data.

Top of Page

Three essential scenarios

Want to hear more? Here are three examples of essential solutions that are based on Business Connectivity Services.

Help desk    A large enterprise has a help desk, which provides internal technical support. Support requests and the technical support knowledge base are stored in an external database, but are fully integrated in a SharePoint site by using external lists and the Business Data Web Parts. Information workers can also view their current requests in Microsoft Outlook 2013 online. Tech support specialists can view requests assigned to them in Outlook 2013 online and offline access. Workflows automatically manage support issues through each stage: Opened, Assigned, Escalated, Resolved, and Closed. Managers on the technical support team, with appropriate permission, can view dashboards that display help desk reports indicating the number of support issues assigned to each support specialist, the most current or critical issues, and the number of support incidents that are handled by each support specialist during a given time period. Managers can also export the data to Microsoft Excel 2013 for further detailed analysis using conditional formatting and charts.

Artist tracker    A talent agency integrates its database of artists into its internal SharePoint team site, which includes a complete list of artists, their contact information, and performance schedules. Recording contracts in the form of Word document templates are generated and automatically filled with the latest artist information. A workflow guides each contract through its various stages. Agents can add new artists to an external list by using an InfoPath form. By using this solution, talent agents always have the information that they need nearby, and they can perform many key tasks by using familiar Office products.

Sales dashboard    A sales dashboard application helps sales associates quickly find sales orders and customer information managed in a Customer Relations Management (CRM) system. Depending on their roles and respective permissions, team members can view sales analytics information, individual team members’ sales performance data, sales leads, and a customer’s contact information and orders. Sales professionals can view their daily calendars, view tasks assigned to them by their managers, collaborate with team members, and read industry news. A Visio diagram of sales territories maps sales by each month and contains live data from the back-end database that is easily refreshed. By using a Word document, managers can quickly author monthly status reports that automatically includes data from the external systems.

Top of Page

Getting there is half the fun

Business Connectivity Services is like a big umbrella that encompasses many SharePoint and Office features. But it doesn’t work “out-of-the-box” because every external data source is unique and each organization has specific needs. Once you lay the groundwork, on-premise or in the cloud, you can surface the external data inside SharePoint products and Office products. When working with external data, you typically go through three distinct phases:

The groundwork phase    During this phase, you plan, prepare, and set up how to access the external data. This usually means working closely with an administrator and sometimes a developer to understand what needs to happen. Important goals are identifying business and technical requirements, preparing the external data source, ensuring secure access to the data by using the Secure Store Service, and scoping the overall solution. A pivotal goal is creating an external content type, which is a detailed package of connections, metadata, and other information used to retrieve the external data.

The SharePoint phase    Once the groundwork has been laid, you can now surface the external data in SharePoint products in a variety of ways, including external lists, external data columns, Business Data Web Parts, workflows, search results, profile pages, actions, Apps for SharePoint, and code-based SharePoint components or solutions.

The Office phase    Once you have created access to the external data in SharePoint products, you can now surface the data in a variety of Office products (including Excel, Word, Outlook, Visio, Access, and InfoPath), Apps for Office, and code-based Office components, add-ins, or solutions.

The three phases of development

You’ll find more details about each of these features later in this article.

Top of Page

Which hat do you wear?

Developing a solution based on external data is usually a team-effort and the way you work depends upon your role. The following diagram shows a high-level view of the roles and solutions that are involved in an overall development life cycle.

Development lifecycle roles and tasks

Users    Users assemble simple solutions by using the basic capabilities of SharePoint products and Office products. Examples include:

  • Creating an external list, different views of the list, and adding various filters and sorts.

  • Exporting the external list to Excel 2013 for further data analysis.

  • Connecting an external list to Outlook 2013 to work with the external data online and offline.

Power Users    Power users create simple to intermediate, no-code business solutions and often require business analyst skills to understand the database systems and the overall business processes in the organization. They also communicate the requirements to administrators and developers, as well as business managers and perhaps site designers. Examples include:

  • Creating an external content type by using Microsoft SharePoint Designer 2013.

  • Creating external data columns in libraries and linking the columns to content controls in a customized Word template, such as a contract or invoice.

  • Customizing InfoPath forms to replace the default SharePoint list forms.

  • Designing a Web page that connects Business Data Web Parts in a useful way to create an information workspace.

  • Creating an Outlook-based solution that provides customized forms, views, ribbon commands, actions, and task panes.

  • Creating a workflow that uses external list data.

Administrators    Administrators manage user permissions and security for several different SharePoint components including the external content type and the external database. A critical activity involves setting up Secure Store Service target applications, mapping of credentials, and determining the best authentication methods. Other examples of operations include:

  • Managing and setting up the external data access, permissions, and queries.

  • Importing and exporting external content types from the Business Data Connectivity metadata store.

  • Setting up custom profile pages, actions, and search results.

Developers    Developers create a variety of custom solutions that range from targeted, reusable components to advanced code-based solutions. Examples include:

  • Advanced external content types developed in Microsoft Visual Studio, such as custom field types that use complex hierarchical data.

  • Aggregated data from multiple services presented as a single BDC model.

  • Reusable components, custom Web Parts, custom workflow activities, and code-behind InfoPath forms.

  • Custom external data parts for Outlook solutions.

  • Microsoft Silverlight applications and Office add-ins.

  • Custom alerts by using the Event Framework.

  • Custom connections or solutions using managed code.

Top of Page

Laying the groundwork

Whatever external data solution you decide to create, you need to create a strong foundation, and that means: getting and setting up the right software, choosing and preparing an external data source, turning on SharePoint services and accounts, and creating an external content type.

Know your SharePoint environment

When you use or create an external data solution, there are differences in features and functionality that you should be aware of based on your SharePoint environment:

  • On-premise    If you create a solution in which your users and your solution are entirely on-premise (behind the firewall), then all Business Connectivity Services features are supported.

  • Cloud    If you are using SharePoint (Plan 2, E3 and E4) in Microsoft 365, then a subset of features are available. For example, external lists, Business Data Web Parts, and the Event framework are supported, but profile pages, actions, and the Connector framework are not. Furthermore, you can only connect to these data sources: WCF Web Services, OData, and SQL Server Azure.

  • Hybrid    Your organization may already have significant investments in on-premise data sources, such as Line-of-Business applications and ERP systems. But your organization may also be in a hybrid SharePoint environment, in which some employees are on-premise and some are in the cloud. In a Hybrid environment, you can also create a hybrid external data solution so that users in the cloud can access an on-premise data source. For example, a user can complete an expense report while on a business trip by using SharePoint, and the charges can be immediately reconciled with an on-premise SAP system. You can connect to any supported on-premise data source, but you must use OData Services and extensive development and configuration may be required.

Get the right software

The features of Business Connectivity Services (BCS) are distributed across different SharePoint editions. Use the following table to help you make the right choice.

Business Connectivity Services Feature

SharePoint Foundation 2013

SharePoint Server 2013 (Standard)

SharePoint Server 2013 (Enterprise)

SharePoint (SPO)
Plan 2
(E3, E4)

Comments

External List

External data column

Business Data Connectivity Services

SPO only supports WCF and SQL Server Azure Connectors

Secure Store Service

SPO only supports group credentials

External Data Search

Profile Pages

Actions

Business Data Web Parts

Office product support

Rich Client Extensions *

App-scoped BCS

Connector framework

Event framework

OData Connector

BCS OM APIs

Hybrid (SPO to On-premise)

Only by using OData Connector

* Includes form controls to display external data and layouts to display data in an Outlook task pane and form region. Available only in Microsoft Office Professional Plus 2013.

Top of Page

Setup the software correctly

Once you have installed the right software, make sure you set it up correctly. In particular:

Prepare the external data source    An administrator may need to create an account and provide permissions to the data source to ensure that the right people have access to the data and that the data does not end up in the wrong hands. In an external database, the administrator may also want to create specific tables, views, queries, and so on to limit the results to just what is needed and to help improve performance.

Configure SharePoint services    An administrator must activate Business Data Connectivity Services, Secure Store Service, and Visio Services.

Configure the Secure Store service    An administrator must determine the best access mode for the external data source, create a target application, and set the credentials for the target application.

Configure Business Data Connectivity Services    An administrator must make sure that the user who creates the external content type has permission to the Business Data Connectivity (BDC) metadata store and that appropriate users have access to the external content type on which the external list is based.

Make sure Office products are ready to use    To synchronize external data with Office products, you must have Windows 7 or later and the following free software products, SQL Server Compact 4.0, .NET Framework 4, and WCF Data Services 5.0 for OData V3 on each client computer (If necessary, you are automatically prompted to download the software). Also, make sure the Office installation option, Business Connectivity Services is enabled (This is the default). This option installs the Business Connectivity Services Client Runtime which does the following: caches and synchronizes with external data, maps business data to external content types, displays the external item picker in Office products, and runs custom solutions inside Office products.

Top of Page

Choose your external data wisely

You can work with a wide variety of external data sources, including databases, Enterprise Resource Planning (ERP) Systems, OData, and advanced connectors.

Databases    Organizations and companies of all shapes and sizes depend on databases for their daily operations. Databases contain a wide variety of data types including text, numbers, images, and documents, and have many purposes including financial, manufacturing, insurance, and data-driven company Web sites. Common supported databases include: Microsoft SQL Server, Oracle, IBM DB2, and any database that complies with ODBC or OLE DB interface standards.

ERP systems    ERP systems integrate Line-of-Business data and processes across an entire organization and perform many of the fundamental activities for any business including:

Business Function

Business Process

Finance and Accounting

General ledger, payables and receivables, cash management, fixed assets, and budgeting

Human resources

Payroll, training, benefits, retirement, recruiting, and diversity management.

Customer relationship management (CRM)

Sales and marketing, commissions, service, customer contact, and call center support.

Manufacturing

Engineering, bill of materials, work orders, scheduling, workflow management, quality control, and product lifecycle management.

Supply chain

Inventory, order entry, purchasing, planning, inspection, and claim processing.

Project management

Costing, billing, time and expense, performance units, and activity management.

Common supported ERP systems include SAP, Duet, Microsoft Dynamics, Siebel, and JD Edwards.

OData    The Open Data protocol (OData) provides a REST-based standard for Create (Post), Read (Get), Update (Put), and Delete (Delete) operations that access Web Services. Think of OData as the web-based equivalent of ODBC and OLE DB. Data is returned either in XML or JavaScript Object Notation (JSON) format. Common OData sources include familiar Web sites (such as Amazon, E-bay, Azure Data Market, and Netflix), databases, and even other SharePoint sites.

Advanced connectors    For other data sources, a developer can provide advanced external data access by:

  • Using ADO.NET, which enables access to any data source with an ADO.NET provider.

  • Using WCF and Web services, which enables access to Web services and Windows Communication Foundation (WCF).

  • Using .NET Connectivity Assemblies, which enables access to data sources when an ADO.NET provider or Web service is unavailable.

  • Converting unsupported proprietary data types to supported .NET data types.

  • Creating custom solutions for larger-scale data sources with frequently changing data structures that require custom data connections, transfer methods, and connector installation.

Top of Page

Consider performance

Any business solution must take performance into consideration, and external data is no exception. Fortunately, Business Connectivity Services has been designed to alleviate many performance bottlenecks and concerns. In general, data retrieval, paging, filtering, and sorting is offloaded to the external data source to help reduce memory and processing resources needed by SharePoint products.

Also, Business Connectivity Services has built-in caches on both server (The Business Connectivity Services cache) and client computers (The Business Connectivity Services Client Runtime cache) and may not display the most recent values from the external data system right away. However, you can adjust the refresh intervals based on the needs of your users and the solutions you create. Not all users need to see up-to-date data right away, but if they do, they can, for example, refresh the external list or Outlook contacts folder.

The ability to work offline on a client computer also means that users can do extended work without being connected to the external data, but know that when they come back online, the data gets updated and reconciled correctly.

Overall, these performance features help speed up the display, refresh, and data operations of the external data on a SharePoint Web page and in an Office product.

Top of Page

Practice safety first

It’s especially vital that an external data solution be secure because the data is often critical to a business and must not be viewed or changed by the wrong users. Also, there are many ways to secure data and you want your solution to be simple as well as safe. Fortunately, there are ways to minimize complexity, primarily by using the Secure Store Service.

In a nutshell, securing your external data requires answering two basic questions:

Who are you?    This is also called authentication and it is the process of verifying your identity by obtaining your credentials (your username and password).

What are you allowed to do?    This is called authorization and it is the process of determining what tasks you can do on which items of data by obtaining the list of permissions you have been granted.

First, an administrator helps determine the best access mode for the external data source. Note that it is very common for business solutions to authenticate access to external data for which the current user has a different account. But logging in under different credentials can be complicated and cumbersome. The Secure Store Service comes to the rescue by providing storage and mapping of credentials. This makes it easier to use an external data source by logging in just once.

For example, if you are logged into your SharePoint site with one set of credentials, but want to access an external list based on a Siebel application that uses another set of credentials, an administrator can set up the Secure Store Service to automatically map the two sets of credentials so that you don’t have to log in again.

The Secure Store Service also helps manage the infamous «double hop» issue, where each authentication requires a “hop” between two computers, which can be compromised, unless steps are taken to prevent it.

How the double hop problem is solved

Next, an administrator creates several layers of security based on permissions, much like several lines of defense around a fort, to ensure appropriate authorization and access to:

  • The data in the external database or system.

  • The external content type in the Business Data Connectivity metadata store.

  • The external list or external data column.

Finally, an administrator can add an extra layer of protection through encryption. if your external data solution also uses Office applications, an administrator can protect the Business Connectivity Services Client Runtime cache by using the Windows Encrypting File System. Some external data sources also provide ways to encrypt the data.

Top of Page

Set the cornerstone: external content types

External content types are at the heart of any external data solution. They are like a broker between you and the external data source. A typical external content type is an organized package of information that contains the following:

  • Connection information to the data source, such as the location, name, and authenticate modes.

  • A definition of the table, fields, primary and foreign keys, validations, and data types (also called metadata).

  • The data operations you can do, such as Create, Read, Update, Delete, and Query (also called CRUDQ).

  • Other information and behaviors, such as mapped Office data types or the enabling of offline synchronization.

  • Various filters, which query the data and help isolate the results, and limits to improve performance.

  • The identity field and display columns for an external content picker used to retrieve external data throughout the user interface.

  • An association based on primary and foreign keys between two related tables, such as Orders and Customers.

One stalwart user defines the external content type and therefore shields other users from the inherent complexity of working with external data. Furthermore all this information is saved in a special BDCM file (.bdcm), in XML format, and stored in the Business Data Connectivity metadata store. This approach makes it easy to maintain, update, secure, and reuse external content types in different sites. For example, you can easily export and import the file to deploy it from a development to a production environment, or share with other site collections.

By the way, your stalwart user doesn’t need to be an expert in XML. To help create an external content type, there are two tools of choice:

  • Microsoft SharePoint Designer 2013    You can define and update the external content type in a declarative way and then publish it to the Business Data Connectivity metadata store.

  • Microsoft Visual Studio 2012    If your external data is complex or is not supported by SharePoint Designer 2013, you can use the XML Editor in Visual Studio (which provides Intellisense) to create your XML model, or use the Visual Studio External Content Type Designer to create a .NET Connectivity Assembly that provides custom back-end integration logic through the .NET Framework.

Top of Page

Surface external data in SharePoint products

Now that you have created a solid and safe foundation for your external data, here’s what you can do with it in SharePoint products.

Read and write data in external lists

An external list is a key building block for SharePoint solutions based on external data. You can read and write external data with the familiar experience of using a SharePoint list. An external list looks and behaves a lot like a native list, but there are some differences in behavior. For example, you can create views and use calculated values with formulas, but not attach files or track versions.

You can also create an external list by using SharePoint Designer 2013.

Top of Page

Add external data columns to lists and libraries

You can combine external data columns with other columns in a native list or library. Because an external data column is added to a native list or library, all related list or library features work, including versioning, approvals, check-in and check-out, and file attachments.

Let’s say you have created a picture library that contains photos of the products your organization sells. You can add an external data column to the library that accesses the product name, product code, and current price from an external database. Because your company rules and processes require any changes to product information only be made through the database system, you specify that the external data is read-only when you create the external content type. But now more people in your organization can easily see all the common product information together in one library view.

Top of Page

Create solutions with Business Data Web Parts

The Business Data Web Parts are designed to work with data from an external list and you can combine these Web Parts in useful ways to create a site workspace or dashboard. For example, you can connect the List and Item Web Parts so that when you select an expense report item in the List Web Part, such as Thursday’s charges, the item details are displayed in the Item Web Part, such as the hotel, travel, and meal charges.

The following table briefly summarizes each Business Data Web Part.

Web Part

Description

Business Data List

Displays a list of items from an external list.

Business Data Item

Displays one or more items from an external list.

Business Data Actions

Displays an action from an external list.

Business Data Connectivity Filter

Filters the contents of connected Business Data Web Part by using a list of values from an external list.

Business Data Item Builder

Creates a Business Data item from parameters in a URL query string and provides it to other Business Data Web Parts.

Business Data Related List

Displays a list of child items related to a parent item from an external list.

Top of Page

Use external data in a profile page, action, or search

Profile pages, actions, and search are closely-related features.

Profile pages

By default, Business Connectivity Services automatically creates a profile page based on the external content type. A profile page is a Web page that displays information from a single row of external data, based on an ID field, such as all the individual fields about a specific customer.

The default profile page is actually a Web page that contains the Business Data Item Builder and a Business Data Item Web Parts connected together. The Item Builder Web Part analyzes the URL query string parameter of the profile page, for example, http://contoso/Customer.aspx?CustID=345, and passes the CustID value to the Data Item Web Part, which then displays all the corresponding customer fields.

You can create your own profile page to show custom information, or an administrator can customize the profile page for you.

Actions

You can even perform an action based on the profile page to do something useful. For example, you can create an action that combines address information about the customer with Bing maps to view the customer’s location or get directions. You can create an action either based on the URL query string parameter of the profile page or through custom code. Or, a developer can write custom code that enables you to update employee information in a back-end database.

By default, you use an action when you click the View Profile action command in a Business Data Actions or Business Data List Web Part. When using an external data column, you can also run the action from a menu command.

Search

Finally if you want, an administrator can enable search of external data. The external data can be crawled and indexed just like internal SharePoint data, but with security trimming to ensure that only the appropriate users can click and see the search results, displayed by using a profile page.

By integrating SharePoint search into external data systems, users can find data they otherwise would not be able to locate. For example, if you know the company a customer works for, but have forgotten their name, you can search by the company name to help you find the customer’s profile page.

Top of Page

Use external data in workflows

Workflows provide a powerful tool for modeling and automating business processes based on a SharePoint list, library, or site. These business processes can be as simple as a document approval process with a single approver, or as complex as any structured business process. Although you cannot directly associate a workflow with an external list, you can create the following:

Native list workflows    A workflow associated with a native list that reads or updates data from an external list by using the Create List Item, Update List Item, and Delete List Item actions. For example, you can update an external list item whenever a native list or library item changes. You can use other actions with external lists, such as the Set Workflow Variable to modify an external list field. You can also use an external list item as a destination for a task process, but the link to the task does not display a title for the external list item.

Site workflows    Site workflows do not require an event trigger to start and can be manually started. To prevent unauthorized access, workflows that access external lists always run in a service account, even with an authentication mode that uses impersonation.

Events    A developer can create events that trigger in the external data source and users can create alerts that respond to these events. For example, you can use a SharePoint workflow to send an email message to an employee when a customer account is assigned to that employee in the external data source.

For performance reasons, it’s good practice to only read a small number of columns in the external list, or create, update or delete a small number of items in the external list.

Top of Page

Surface external data in Office products

Now that you have surfaced the data in SharePoint products, here’s what you can do with it in various Office products.

Analyze external data in Excel

You can export data from an external list to Excel 2013 and keep the data synchronized. For example you may want to maintain a product inventory in an external list so that it’s easy to share and update, but also do periodic inventory analysis in Excel 2013. The external data that is exported to Excel 2013 is determined by the current external list view, the filters defined on the external content type and in the external list, and the language settings for the SharePoint site.h

When you export an external list, an Excel Table is created with a data connection to the external list based on a Web query file. To see further changes made to the SharePoint list in the Excel Table, you can refresh the data. Note that you cannot make changes to the source of the external data and that an Excel refresh operation would overwrite any changes you have made in the Excel Table.

Top of Page

Add external data to Word documents

By adding external data columns and a Word template with content controls to a document library, you can also make it easy and efficient to enter accurate, up-to-date data in a Microsoft Word 2013 structured document.

Let’s say you have a document library that contains customer contracts. However, all your customer information is maintained in a Line-of-Business application, such as SAP. You can track the customer’s contracts in the document library, but ensure that related customer information is up-to-date and not unnecessarily duplicated. Here’s how:

  • First, add external data columns to the library to associate the appropriate customer name, company name, and telephone number with each contract stored in the Contract library.

  • Then, create a Word template that contains the customer contract boilerplate text and content controls to enter the customer name, company name, and telephone number. Word 2013 will use the external item picker to help you enter or update the correct information by automatically displaying and retrieving the correct customer information.

  • Finally, each time you create a contract, enter customer data, and save the contract back to the library, the customer data values are promoted to the corresponding external data columns.

Top of Page

Synchronize external data in Outlook

If an external list contains customers, tasks, appointments, or posts, you can connect the list with Outlook 2013. Once connected, you can view, edit, and print the data using the familiar Outlook user interface. If the data is contact information, such as customers, you can even call them, send them e-mail messages, and make meeting requests.

The synchronization of the data is two-way or bi-directional. Changes made in Outlook 2013 are automatically synchronized with the external data source. Changes made to the external data source are synchronized with the items in Outlook 2013, although a refresh operation may be needed.

By default, the data automatically refreshes every six hours, but this value can be changed. To make sure you are seeing current data from the external data source, right-click the folder and then click Sync DB changes.

When you create the external content type, you do the following:

  • If you want offline access, enable the Offline Sync support option.

  • Set the Office Item Type field to one of the following: Contact, Appointment, Task, or Post.

  • Map the individual fields in the external content type, such as Customer First Name, Customer Last Name, Customer Address, and Customer Phone, to their respective Outlook Item Type fields, such as a contact’s FirstName, LastName, BusinessAddress, and BusinessPhone.

Additionally, with some code written by a developer, you can create an Outlook solution that does the following:

  • Show native or custom data parts in custom task panes to present external data to users.

  • Include custom ribbon commands to perform custom actions.

  • Create a custom view definition to display specific columns of external data.

  • Design custom form regions to present external data.

Top of Page

Enhance external data access with InfoPath forms

There are a number of reasons why Microsoft InfoPath 2013 is useful to use with external data:

Working with complex data types    If a field of external data is hierarchical, such as an address field that contains Street, City, and Postal code as a subfields, then you cannot work with this field in the SharePoint form for an external list, and in fact it is not even created. However, you can convert the SharePoint form to an InfoPath form to create and update the fields by using InfoPath 2013.

Embedding an External Item Picker Control    You can drag and drop the External Item Picker control onto an InfoPath form, link it to the external list as a secondary data source, and make it easy for a user to select an item based on a unique field, such as a Customer Name or Product ID.

Furthermore, if you set up an association for external content types, such as customers and orders, and the InfoPath form for the external list contains a foreign key, such as Customer ID, the External Item Picker control is even automatically added to the form. This enables users to easily find the customer they want when working with orders.

Creating Multiple Views of a Form    Sometimes, you may want forms to have multiple views of your external data, especially if there are many fields and an external list or SharePoint form is not effective. Multiple views are also useful in write-once scenarios where the external system does not allow updating a field after it is created. In such cases, you can create two views, one for the create operation and the other for the update operation.

Adding Rules or code-behind to forms    You can add declarative rules or code-behind forms to perform additional business logic, such as validation and calculations. For example, you can ensure a country/region code is valid by using a rule, or U.S. postal code is valid by using a Web Service.

Top of Page

Add external data to published Visio diagrams

Using Microsoft Visio 2013, you can link data from an external list to a diagram and it’s shapes. You can then publish the diagram to a SharePoint document library as an interactive Web drawing so users can display the diagram and view the associated external data. There are three ways to link rows of data to shapes in your drawing. You can link rows to existing shapes one at a time, you can link the rows to shapes automatically, or you can create shapes from the data.

Top of Page

Import and refresh external data in Access

Microsoft Access 2013 is a landing pad for all types of data and external data is no exception. You can import an external list to your Access database on your client computer and periodically refresh the data. The data is read-only.

The basic steps to follow are:

  1. Export the external content type from SharePoint Designer 2013 or directly from the Business Data Connectivity metadata store as a BDCM file.

  2. In Access 2013, create a Web Service data connection by using the BDCM file.

  3. In Access 2013, create a linked table based on the Web Service data connection.

Note that in this case, the Business Connectivity Services Client Runtime cache is not used to synchronize with the external list when you refresh the data.

Top of Page

Definition. External data refers to any type of data that has been captured, processed, and provided from outside the company.

Contents

  • 1 What is an example of external data?
  • 2 What is internal and external data?
  • 3 Why is external data important?
  • 4 What is external data store?
  • 5 What is external data in Excel?
  • 6 What is external primary data?
  • 7 What are internal data?
  • 8 What are examples of internal data?
  • 9 What is external research?
  • 10 What is syndicated data source?
  • 11 What do you understand by primary data?
  • 12 What is Open Data used for?
  • 13 What is external memory in phone?
  • 14 What are external data services?
  • 15 What is the use of external data tab?
  • 16 How do I remove external data connections?
  • 17 How do I find external data in Excel?
  • 18 How do I use an external data source in Excel?
  • 19 What is secondary external data?
  • 20 What are three sources of external data?

What is an example of external data?

External data — Data from outside sources
Publicly available data such as census, electoral statistics, tax records and internet searches. Private data from third parties such as Amazon, Facebook, Google, Walmart and credit reporting agencies like Experian.

What is internal and external data?

Internal data is information generated from within the business, covering areas such as operations, maintenance, personnel, and finance. External data comes from the market, including customers and competitors. It’s things like statistics from surveys, questionnaires, research, and customer feedback.

Why is external data important?

External data — from outside your own company — is important to your data warehouse for one simple reason: To ensure that you make the right business decisions, you need to see the big picture, which usually means you can’t find all the answers stored in your company’s various computer applications and databases.

An external storage device, also referred to as auxiliary storage and secondary storage, is a device that contains all the addressable data storage that is not inside a computer’s main storage or memory.

What is external data in Excel?

External data is defined as data that exists outside of the Excel workbook, in some other place. That other place could be almost anywhere, and Excel supports pulling external data from a wide variety of sources. Examples include data stored on web pages, in text files, or in other programs.

What is external primary data?

Primary data is data gathered for the first time by the researcher; secondary data is data taken by the researcher from secondary sources, internal or external.Secondary data – whether internal or external – is data already collected by others, for purposes other than the solution of the problem on hand.

What are internal data?

Internal data is information, statistics, and trends that organizations discover through their operations. It includes facts and figures that companies pull from internal databases, software, customers, and reports.

What are examples of internal data?

Internal data may include the following:

  • sales trends and metrics.
  • customer habits.
  • software user trends.
  • operational trends.
  • leadership decision-making.
  • marketing data.
  • internal research.
  • cash flow reports.

What is external research?

External Research means consultation with and the written opinions, analysis, research or other work product of third party technical specialists, legal counsel or other advisors, consultants or professionals.

What is syndicated data source?

Syndicated data refers to general market data that isn’t specific to any one client. An aggregation of retailer and product data, syndicated data is generally collected by market research firms and then purchased by businesses who have a vested interest in the market.

What do you understand by primary data?

Primary Data: It is a term for data collected at source.Primary data means original data that has been collected specially for the purpose in mind.It means someone collected the data from the original source first hand. Primary data has not been published yet and is more reliable, authentic and objective.

What is Open Data used for?

Open data is data that anyone can access, use and share. Governments, businesses and individuals can use open data to bring about social, economic and environmental benefits.

What is external memory in phone?

Primary External Storage is one that is accessible by the user but still part of the built-in memory. That’s where you store your photos, documents, and other data even though when you don’t have an SD card installed. In short, your phone’s built-in memory is divided into two parts. Internal and external.

What are external data services?

The external data service is invoked when a user opens a certain dialog box or tries to set a value on a property in the user interface.

What is the use of external data tab?

a) Get External Data: – In Excel, we can import data from MS Access, Web, Text and other sources. Also, we can import the data from other applications. b) Connections: -It is used to display the entire data connections for the workbook.

How do I remove external data connections?

Delete an external data range

  1. Click the worksheet that contains the external data range that you want to delete.
  2. On the formula bar, click the arrow next to the Name Box, and then click the name of the external data range that you want to delete.
  3. To delete the external data range, press DELETE.

How do I find external data in Excel?

To open the Existing Connections dialog box, select Data > Existing Connections. You can display all the connections available to you and Excel tables in your workbook. You can open a connection or table from the list and then use the Import Data dialog box to decide how you want to import the data.

How do I use an external data source in Excel?

Click any cell on the worksheet. Click Insert > PivotTable. In the Create PivotTable dialog box, under Choose the data that you want to analyze, click Use an external data source. Click Choose Connection.

What is secondary external data?

Existing data that have already been collected by other organisations.

What are three sources of external data?

The main sources of external secondary sources are (1) government (federal, state and local) (2) trade associations (3) commercial services (4) national and international institutions. Agricultural statistics.

Often, we use Excel to summarize detail that comes from some other program or accounting system. There are essentially three ways that I am aware of to get data from another program into a destination Excel worksheet, I’ll nickname them:

  • Copy/Paste
  • Pull
  • Push

Copy/Paste

The Copy/Paste method is probably the most common.  It is when you basically view or export the data to a new Excel, csv or text file, and then copy and paste the data into the destination Excel worksheet..  It is easy to use and works well. However, other methods may be more efficient for recurring use workbooks.

Pull

You can pull the data directly from the external data source using the External Data feature of Excel. This post focuses on this feature, and the details are found below.

Push

You can also push the data from the system into a specific worksheet in an existing workbook.  Not all applications support this method, but when they do, it will save a step.

Now, let’s spend the rest of our time working through the External Data feature.

External Data

The External Data feature has been in Excel for a long time, and I first started using it in about 1997.  This feature made a big improvement in my workflow and increased my productivity.  Since then, I’ve been a huge fan of this feature! It is one of those things that is just sitting there waiting to be discovered and put to use.

External Data Overview

First, let’s start with what the feature does, and then we’ll move on to how to use it.  External data is defined as data that exists outside of the Excel workbook, in some other place.  That other place could be almost anywhere, and Excel supports pulling external data from a wide variety of sources.  Examples include data stored on web pages, in text files, or in other programs.

Programs that store large amounts of data are often built upon a database engine or platform. You, as the user, see the program’s user interface which is made up of menus, icons, dialog boxes, and forms.  Behind the scenes however, applications often store their data in a database.  It is this underlying database that Excel can often tap into with the External Data feature.

This feature doesn’t pull a single value into a single cell.  It retrieves a block of data, or a table, that will ultimately occupy a range of cells.

The External Data feature asks you to identify the location of the data you want. Once you do, Excel retrieves the data and places it into the selected worksheet. The best part of this feature lies in the fact that the External Data range is not static….it can be refreshed.  When you click the refresh button, Excel heads out to the data source and pulls back the updated data.  This improves the efficiency of recurring use workbooks because you don’t need to do the whole export, import, reformat routine that is needed with the standard copy/paste method.  You simply click the refresh button, and bam, the updated data just appears in your worksheet.

How to Pull External Data

Excel supports pulling data from a wide variety of data sources.  Examples include web pages, text files such as csv files, SQL, Access, ODBC compliant sources, and more.  The basic process is that you first identify the type of data source and then the location.  Depending on the type of source, you’ll have appropriate options. For example, if you are pulling data from an Access database, you’ll identify the table or query, and then which columns and rows you want.

For this post, I wanted to use a data source that you’ll have access to in case you want to work along. So, we’ll pull some external data from a web page.

We tell Excel that we want to retrieve data from an external source by first identifying the type of source. This is done by selecting the appropriate ribbon icon from the Data tab as shown below.

External Data Icons

For this simple example, we want to get data from a web page.  Our objective is to pull historical closing stock prices for Apple.  So we click the From Web icon from the Data ribbon.  This will reveal the next step in the process, which is to identify the web page.  We’ll head over to the Yahoo Finance page, so we enter the URL  http://finance.yahoo.com into the address field, as shown below.

Excel External Data Web

Next, we enter the stock symbol AAPL for Apple into the web page, and click the Get Quotes button.  We scroll down the page a bit, until we see the “Historical Prices” link on the left.  We click it, and we can see the daily closing prices.  We click the yellow arrow for the Prices table, and see that Excel identifies the range with a border and changes the yellow arrow to a green check, as shown below.

Excel Web Table

Next, we click the Import button and then tell Excel where we want the data to be placed, and bam, we have it in our Excel worksheet, as shown below.

Excel External Stock Price Data Table

The best part is that if we want to refresh the data, we don’t need to go through all of the setup steps again, we just need to click the refresh button on the Data ribbon tab, or, right-click the external data range and select Refresh.  Excel will go back to the data source, retrieve the updated data and drop it, automagically, into the worksheet.

Recap

For recurring processes, the External Data feature is probably more efficient than the standard copy/paste approach since you simply click the Refresh button to retrieve updated data. There are many external data sources that are compatible with this feature.  This post only provided a simple warm-up.  There is a lot more to explore as this feature supports a wide range of data types, sources, and options.  You can even set up a parameter query, where the criteria is placed in an Excel worksheet.  The criteria values stored in Excel are relayed to the external data source during the retrieval, and this makes it easy to filter the data before it hits the worksheet.  Excel Rules!

External data is defined as data that exists outside of the Excel workbook, in some other place.  Other places could be almost anywhere; and Excel supports pulling external data from a wide variety of sources.  Examples include data stored on web pages, in text files, or in other programs.

Excel 2007 is been used in below examples.

We get external data in excel by using different ways:-

  1.  From Access
  2.  From Web
  3. From Text
  4. From Other Sources
  •         From SQL Server
  •         From XML Data Import

I) Import Access Data

In Excel, when you import data, you make a permanent connection that can be refreshed.

  1. On the Data tab, in the Get External Data group, click From Access.
  2. Select the Access file.
  3. Click Open.
  4. Select a table and click OK. 
  5. Select how you want to view this data, where you want to put it, and click OK. 

Result. Your database records in Excel.

  1. When your Access data changes, you can easily refresh the data in Excel. First, select a cell inside the table. Next, on the Design tab, in the External Table Data group, click Refresh.

II) Import Web Data

  1. On the Data tab, in the Get External Data group, click From Web.

 

  1. When you select From Web Excel opens a dialog box displaying your browser homepage with the URL of the page highlighted. Paste the copied web address into the Address box. A quick way to paste is to Hold down the Ctrl Key as you tap one time on the V key( Ctrl + V ). You may have to scroll to find the data table. When you find it, click one time on the arrow next to the Data table and then click on the Import button.

  1. You have a choice to make. Excel is ready to import the data, but needs to know if you want it put into the existing workbook, or a new workbook.

III) Import Text Data

  1. On the ribbon, click the data tab and then click the “From Text” button on the “Get External data” group.

The “From Text” button, located on the Data tab of the ribbon.

  1. Select your file from the next dialog:

And Click Import.

  1. Now it is time to define what settings we need for the import.Click the Open button. The text import wizard opens up:

Step 1 of the Text Import Wizard, define file type.

In this example I have selected to import a delimited file and set the file origin to Windows (ANSI). Click Next when you’re happy with the settings.

  1. Step 2 of the wizard allows us to define the delimiters. I selected Comma:

Step 2 of the Text Import Wizard: define delimiters.

  1. Click Next again to go into the third step, where you can select a format for each column of your file. I changed the date format of the first column to dmy order. Click a column to set up its formatting.

Step 3 of the wizard, Define column formats.

You can click the advanced button to set up details like the decimal and thousands separators (note I switched them here):

The Advanced text Import Settings dialog.

Note that any changes made in this dialog apply to all columns.

  1. After you finished defining all columns, click the Finish button. Excel opens the Import Data dialog, asking where to put the results. Select the proper location.

The Import Data dialog.

  1. Import your data

Finally, click OK to have your data imported. My sheet looks like this:

Results after importing the text file.

  1. Refresh your data

On the Data tab, find the group called “Connections”. Click the dropdown “Refresh All” and select “Refresh”:

The Refresh All button on the ribbon.

IV) Import Data from Other Sources

  • Import SQL Server Data 

On the Data tab, in the Get External Data group, click From Other Sources.

  1. Click From SQL Server.

  1. In the Data Connection Wizard, enter the server name and logon credentials, and click Next.

  1. Choose the database and tables you want to work with, and click Next.

  1. You can click Finish, or click Next to change details for the connection.

  1. In the Import Data dialog box that appears, choose where to put the data in your workbook and whether to view the data as a table, Pivot Table report, or Pivot Chart. 
  2. Import your data

Finally, click OK to have your data imported. My sheet looks like this:

  • Import XML Data Files

On the Data tab, in the Get External Data group, click From Other Sources.

  1. From Other Sources > From XML Data Import
  2. Go to the drive, folder, or Internet location that has the XML data file (.xml) you want to import. Select the file and click Open
  3. In the Import Datadialog box, do one of the following:
    • XML table in existing worksheet: The contents of the file are imported into a new XML table in a new worksheet. If the XML data file doesn’t refer to a schema, Excel infers the schema from the XML data file. 
    • Existing worksheet: The XML data is imported in a two-dimensional table with rows and columns that shows XML tags as column headings, and data in rows below the column headings. The first element (the root node) is used like a title and is displayed in the specified cell location. The rest of the tags are sorted alphabetically across the second row. In this case, Excel doesn’t infer a schema, and you can’t use an XML Map. 
    • New worksheet: Excel adds a new worksheet to your workbook and automatically puts the XML data in the upper-left corner of the new worksheet. If the XML data file doesn’t refer to a schema, Excel infers the schema from the XML data file.

  1. Excel sheet will look like this:

References

  • https://www.gcflearnfree.org/excel2007
  • https://support.office.com/en-US/Excel

About Suman Maity:

Suman Maity is a B.Tech(Electrical Engineering) . Currently he is working as an Analyst Intern with NikhilGuru Consulting Analytics Service LLP, Bangalore. He has prior worked for around 1+ year with T&M Services Consulting Pvt Ltd and HR Chamber Outsourcing Pvt Ltd.

Содержание

  1. Connect Your Data Sources and Automate Updates with Excel Data Connection
  2. Creating a data connection
  3. Refreshing and managing data connections
  4. Connect to (Import) external data
  5. Find out which data sources are used in a workbook data model
  6. Need more help?
  7. Work with external data in Excel Services (SharePoint Server)
  8. In this article
  9. What is external data?
  10. Data sources that are supported in Excel Services
  11. Excel Web App and Excel Services
  12. Determining whether Excel Services or Excel Web App is used to render a workbook
  13. External data sources that are supported in Excel Services and Excel Web App

Connect Your Data Sources and Automate Updates with Excel Data Connection

by Adam | Sep 5, 2018 | Blog

Although Excel does a great job at saving data in a nice table structure, some projects require data to be stored or exported elsewhere. Text files, other excel files, databases, or even web pages can be used as a means to consume or store data. If you need to periodically update your data, moving or copying to an Excel spreadsheet can be time consuming and prone to errors. Data connection features of Excel can help establish permanent links with other data sources and automate this process.

Excel can pull data from an external data source into your spreadsheet with the help of data connection features. Excel can connect external data sources when you provide certain information about the external data and allows you to refresh them manually, automatically in specified intervals, or in a more customized fashion using VBA. In this article, we’re going to be using an equipment rental data and connect it with data from a Microsoft Access database. You can download the workbook and the Access file below.

Data connection features can be found under the DATA tab and consists of two categories:

  • Get External Data
  • Connections

Features under the Get External Data section help create a connection with sources like other workbooks, databases, text files, or websites. Connections section contains features for managing existing connections. To begin creating a new link, click Connections. You will be taken to the Workbook Connections window.

When you connect an external data in Excel, data will be first saved in the workbook. This data can then be exported in other formats, such as Office Data Connection (ODC) (.odc), or a Universal Data Connection (UDC) file (.udcx), to save or share the information.

Creating a data connection

Follow the steps below to connect an external data source to your workbook.

  1. Begin by going to the Data tab and selecting the connection type that corresponds to your data source. In this example, we are using a Microsoft Access database. Please note that the exact steps will be different if you choose another data type. For example, while you need to select a file for an Access or a text file, you will need to enter the server address for a SQL database. Click the From Access icon to connect to an Access file.
  2. Select your file and click Open.
  3. Select Table window will appear. Select the table you’d like to use and click OK to continue.
  4. In the Import Data window, you can choose how and where to display your data, and you can access advanced settings by pressing the Properties You don’t have to this now as you can open the Properties window at any time after creating connection.

In our example, we choose the Table option. Here is brief summary of all options.

  • Table: Data is displayed in a tabular form
  • PivotTable Report: You can use the columns to create a PivotTable
  • PivotChart: You can use the columns to create a PivotChart
  • Only Create Connection: Data will not be displayed, but the connection can be used by other features or VBA, and can be exported.
  • Add this data to Data Model: Data is added to the Power Pivot Data Model. This option is independent from the display option above. However, it is advisable to use it with Only Create Connection option, because you can manage your data better in the Data Model.

You can choose to pull certain columns, instead of the entire table, if necessary. Try the PivotTable and Only Create Connection options to create connections without displaying the data in your spreadsheet.

Refreshing and managing data connections

There are several ways to refresh existing connections. The first method is by using the icons under both DATA and TABLE TOOLS — DESIGN tabs in the ribbon. These icons can be used to refresh data connection manually.

Both options essentially do the same thing. However, the default actions are different for the Refresh buttons in the DATA and TABLE TOOLS – DESIGN tabs. While Refresh All action is the default action in DATA tab. Refresh action is the default in the TABLE TOOLS – DESIGN tab. The Refresh button only refreshes the active table’s connection.

Power Pivot and Power Query windows also contain refresh buttons.

To automate this process, you can set a time interval to refresh data connections. To set a refresh interval, and manage the connections (including advanced Properties), use the Connections button to open the Workbook Connections window. You can add new connections, or refresh existing ones in this menu. Select the existing connection and click the Properties button to open Connection Properties window.

Enable the Refresh every option and modify the number that represents minutes. When you click OK, your data connection will be updated in selected intervals.

An alternative way to automatically refresh data is using VBA. This allows combining data connection features with your own custom code. Below is sample codes that can refresh data connections.

Источник

Connect to (Import) external data

The main benefit of connecting to external data is that you can periodically analyze this data in Microsoft Office Excel without repeatedly copying the data, which is an operation that can be time-consuming and error-prone. After connecting to external data, you can also automatically refresh (or update) your Excel workbooks from the original data source whenever the data source is updated with new information.

Important: Connections to external data may be disabled on your computer. To connect to data when you open a workbook, you must enable data connections by using the Trust Center bar. For more information, see Add, remove, or view a trusted publisher, Trusted documents, and View my options and settings in the Microsoft Office Trust Center.

To open the Existing Connections dialog box, select Data > Existing Connections. You can display all the connections available to you and Excel tables in your workbook. You can open a connection or table from the list and then use the Import Data dialog box to decide how you want to import the data.

Note: You can also open the Existing Connections dialog box from the Change PivotTable Data Source dialog box. For more information about changing the data source for a PivotTable, see Change the source data for a PivotTable.

In the Show drop-down list, do one of the following:

All To display all connections, click All Connections. This is selected by default.

Workbook To display only the recently used list of connections, click Connections in this Workbook.

This list is created from connections that you have already defined, that you have created by using the Select Data Source dialog box of the Data Connection Wizard, or that you have previously selected as a connection from this dialog box.

Computer To display only the connections that are available on your computer, select Connection files on this computer.

This list is created from the My Data Sources folder that is usually stored in the My Documents folder on your computer.

Network To display only the connections that are available from a connection file that is accessible from the network, select Connection files on the Network. This list is created from an Excel Data Connection Library (DCL) on a Microsoft SharePoint Services site. A DCL is a document library in a SharePoint Services site that contains a collection of Office Data Connection (ODC) files (.odc). Typically, a DCL is set up by a site administrator, who can also configure the SharePoint site to display ODC files from this DCL in the External Connections dialog box. For more information, see SharePoint Services Central Administration Help.

Select the connection that you want, and then select Open. The Import Data dialog box appears.

Decide how you want to import the data, and then select OK. For more information about using this dialog box, select the question mark (?).

Tip: If you do not see the connection that you want, you can create a connection. Click Browse for More, and then in the Select Data Source dialog box, click New Source to start the Data Connection Wizard so that you can select the data source that you want to connect to.

Note: If you choose a connection from the Connection files on the network or Connection files on this computer categories, the connection file is copied into the workbook as a new workbook connection, and is then used as the new connection information.

In the Show drop-down list, do one of the following:

All To display all connections, click Workbook Tables. This is selected by default.

Connections To display tables defined only by a connection select Connections Tables.

This list is created from connections that you have already defined, that you have created by using the Select Data Source dialog box of the Data Connection Wizard, or that you have previously selected as a connection from this dialog box.

Workbook To display a table in the workbook select Workbook Tables.

Select the connection that you want, and then select Open. The Import Data dialog box appears.

Decide how you want to import the data, and then select OK. For more information about using this dialog box, select the question mark (?).

Источник

Find out which data sources are used in a workbook data model

If you’re working with data that’s been added to an Excel data model, then sometimes, you may lose track of which tables and data sources were added to the data model.

Note: Make sure you have enabled the Power Pivot add-in. For more information, see Start the Power Pivot add-in for Excel.

Here are a few easy steps you can follow to determine exactly what data exists in the model:

In Excel, click Power Pivot > Manage to open the Power Pivot window.

View the tabs in the Power Pivot window.

Each tab contains a table in your model. Columns in each table appear as fields in a PivotTable Field List. Any column that is grayed-out has been hidden from client applications.

To view the origin of the table, click Table Properties.

If Table Properties is grayed out and the tab contains a link icon indicating a linked table, the data originates from a sheet in the workbook rather than an external data source.

For all other types of data, the Edit Table Properties dialog shows the connection name and query used to retrieve the data. Make a note of the connection name, and then use Connection Manager in Excel to determine the network resource and database used in the connection:

In Excel, click Data > Connections.

Select the connection used to populate the table in your model.

Click Properties > Definition to view the connection string.

Note: Data models were introduced in Excel 2013. You use them to create PivotTables, PivotCharts, and Power View reports that visualize data from multiple tables. Learn more about data models in Create a Data Model in Excel.

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Источник

Work with external data in Excel Services (SharePoint Server)

Note: This article assumes that you are using the version of Excel that comes with Office Professional Plus. Excel Starter and the version of Excel that comes with the Home and Student editions of Office do not support external data connectivity as described in this article.

The information in this article applies to Excel Services in SharePoint Server 2013 (on premises) only. For information about Microsoft 365 (in the cloud), see Use external data in workbooks in SharePoint Online.

You can work with a wide variety of data sources in Excel, including native data and external data. Some, but not all, of the external data sources that you can use in Excel are supported in Excel Services. Read this article to get an overview of what’s supported in Excel Services when you publish a workbook to a SharePoint library.

In this article

What is external data?

External data is data that is stored someplace else, such as on a server. You can import or display external data in a workbook by using one or more external data connections. Examples of external data sources can include SQL Server tables, SQL Server Analysis Services cubes, Microsoft Azure Marketplace data, and so on. External data connections that are used in a workbook make it possible to send queries and receive data from the databases that are specified in the connections. This enables you to refresh the data to view the most current information in a workbook.

As an alternative to working with external data, you can use native data in Excel. Native data is stored directly in the workbook, and does not require an external data connection to be retained, even if an external connection was used to import data into a workbook. To update native data, you can manually type updates or reimport data into Excel.

Data sources that are supported in Excel Services

Some, but not all, of the data sources that you can use in Excel are supported in Excel Services in SharePoint Server 2013. When a data source is supported in Excel Services, it means that you and other users are able to refresh the data that is displayed in a workbook. Excel Services in SharePoint Server 2013 supports the following kinds of data sources:

SQL Server tables

SQL Server Analysis Services cubes

OLE DB or ODBC data sources

Data models, such as those that are created in Excel

Excel Web App and Excel Services

If your organization is using Office Web Apps alongside SharePoint Server 2013, then either Excel Services (part of SharePoint Server 2013) or Excel Web App (part of Office Web Apps Server) is used to render workbooks in a browser window. This is a decision that SharePoint administrators make, and it can affect which data sources are supported when you are using a workbook in a browser window. For more information, see Comparing Excel Online, Excel Services, and Excel Web App.

Determining whether Excel Services or Excel Web App is used to render a workbook

You might be wondering how to tell if you are using Excel Services or Excel Web App when you view a workbook in a browser window. One way to do this is to examine the website address (URL) for the workbook.

Look for xlviewer in the URL.
If the URL resembles http://[servername]_layouts/15/xlviewer.aspx?id=/Documents/. , then Excel Services is used to render the workbook.

Look for WopiFrame in the URL.
If the URL resembles http://[servername]/_layouts/15/WopiFrame2.aspx?sourcedoc=/Documents/. , then Excel Web App is used to render the workbook.

You can also contact your SharePoint administrator for help with information about how your environment is configured.

External data sources that are supported in Excel Services and Excel Web App

The following table summarizes the kinds of data connections that you can use in Excel and which data connections are supported in Excel Services and in Excel Web App.

Excel Data Source

Supported in Excel Services (SharePoint Server)?

Supported in Excel Web App (Office Web Apps Server)?

SQL Server tables

Yes, if the environment includes SharePoint Server 2013 and it is configured to use Secure Store Service or an unattended service account. Contact a SharePoint administrator for more information.

SQL Server Analysis Services cubes

Yes, if the environment includes SharePoint Server 2013 and it is configured to use Secure Store Service or an unattended service account. Contact a SharePoint administrator for more information.

OLE DB or ODBC data sources

Yes, if each connection’s string contains a user name and password. Contact a SharePoint administrator for more information.

Yes, if each connection’s string contains a user name and password. Contact a SharePoint administrator for more information.

Data model that was created by using Excel

Yes, if Excel Services is configured to support data models. Contact a SharePoint administrator for more information.

Источник

Содержание

  1. Как это работает
  2. Подключаем внешние данные из интернет
  3. Импорт внешних данных Excel 2010
  4. Отличите нового и старого мастера импорта
  5. Пример работы функции БИЗВЛЕЧЬ при выборке данных из таблицы Excel
  6. Примеры использования функции БИЗВЛЕЧЬ в Excel
  7. Тип данных: Числовые значения MS Excel
  8. Классификация типов данных
  9. Текстовые значения
  10. Дата и время
  11. Логические данные
  12. Разновидности типов данных
  13. Число
  14. Текст
  15. Ошибки
  16. Подключение к внешним данным
  17. Подключение к базе данных
  18. Импорт данных из базы данных Microsoft Access
  19. Импорт данных с веб-страницы
  20. Копировать-вставить данные из Интернета
  21. Импорт данных из текстового файла
  22. Импорт данных из другой книги
  23. Импорт данных из других источников
  24. Задача для получения данных в Excel

Как это работает

Инструменты для импорта расположены во вкладке меню «Данные».
Если подключение отключено, перейдите:
Далее:
На вкладке «Центр управления» перейдите:

Подключаем внешние данные из интернет

В Excel 2013 и более поздних версиях, по умолчанию для импорта информации из внешних источников используется надстройка Power Query. Как это работает? Перейдите:
Пропишите адрес сайта, с которого импортируются данные:
Выберите что отобразится, нажмите кнопку «Загрузить».
Информация подгрузится в лист Excel. Работайте с ними как с простым документом: используйте формулы графики, сводные таблицы.
Для обновления нажмите ПКМ по таблице:
Или:

Импорт внешних данных Excel 2010

Перейдите:
В новом окне пропишите адрес сайта. Получите информацию из областей страницы, где проставлены желтые ярлыки. Отметьте их мышкой, нажмите «Импорт».
Отметьте пункт «Обновление». Тогда внешняя информация обновится автоматически.

Отличите нового и старого мастера импорта

Преимущества Power Query:

  1. Поддерживается работа с большим числом страниц;
  2. Промежуточная обработка информации перед загрузкой на лист;
  3. Информация импортируется быстрее.

Как создать базу данных в Excel? Базой данных в программе Excel считается таблица, которая была создана с учетом определенных требований:

  1. Заголовки таблицы должны находиться в первой строке.
  2. Любая последующая строка должна содержать хотя бы одну непустую ячейку.
  3. Объединения ячеек в любых строках запрещены.
  4. Для каждой ячейки каждого столбца должен быть определен единый тип хранящихся данных.
  5. Диапазон базы данных должен быть отформатирован в качестве списка и иметь свое имя.

Таким образом, практически любая таблица в Excel может быть преобразована в базу данных. Ее строки являются записями, а столбцы – полями данных.

Функция БИЗВЛЕЧЬ хорошо работает с корректно отформатированными таблицами.

Примеры использования функции БИЗВЛЕЧЬ в Excel

Пример 1. В таблице, которую можно рассматривать как БД, содержатся данные о различных моделях смартфонов. Найти название бренда смартфона, который содержит процессор с минимальным числом ядер.

Вид таблиц данных и критериев:

В ячейке B2 запишем условие отбора данных следующим способом:

=МИН(СТОЛБЕЦ(B1))

Данный вариант записи позволяет унифицировать критерий для поиска данных в изменяющейся таблице (если число записей будет увеличиваться или уменьшаться со временем).

В результате получим следующее:

В ячейке A4 запишем следующую формулу:

Описание аргументов:

  • A8:F15 – диапазон ячеек, в которых хранится БД;
  • 1 – числовое указание номера поля (столбца), из которого будет выводиться значение (необходимо вывести Бренд);
  • A2:F3 – диапазон ячеек, в которых хранится таблица критериев.

Результат вычислений:

При изменении значений в таблице параметров условий мы будем автоматически получать выборку соответственных им результатов.

Тип данных: Числовые значения MS Excel

Числовые значения, в отличие от текстовых, можно и складывать и умножать и вообще, применять к ним весь богатый арсенал экселевских средств по обработке данных. После ввода в пустую ячейку MS Excel, числовые значения выравнивается по правой границе ячейки.

Фактически, к числовым типам данных относятся:

  • сами числа (и целые и дробные и отрицательные и даже записанные в виде процентов)
  • дата и время

Несколько особенностей числовых типов данных

Если введенное число не помещается в ячейку, то оно будет представлено в экспоненциальной форму представления, здорово пугающей неподготовленных пользователей. Например, гигантское число 4353453453453450 х 54545 в ячейку будет записано в виде 2,37459Е+20. Но, как правило в «жизни» появление «странных чисел» в ячейках excel свидетельствует о простой ошибке.

Если число или дата не помещается в ячейку целиком, вместо цифр в ней появляются символы ###. В этом случае «лечение» ещё более простое — нужно просто увеличить ширину столбца таблицы.

Иногда есть необходимостью записать число как текст, например в случае записи всевозможных артикулов товаров и т.п. дело в том, что если вы запишите 000335 в ячейку, Excel посчитав это значение числом, сразу же удалит нули, превратив артикул в 335. Чтобы этого не произошло, просто поместите число в кавычки — это будет сигналом для Excel, что содержимое ячейки надо воспринимать как текст, то есть выводить также, как его ввел пользователь. Естественно, производить с таким числом математических операций нельзя.

Что представляет собой дата в MS Excel?

Если с числами все более-менее понятно, то даты имеют несколько особенностей, о которых стоит упомянуть. Для начала, что такое «дата» с точки зрения MS Excel? На самом деле все не так уж и просто.

Дата в Excel — это число дней, отсчитанных до сегодняшнего дня, от некой начальной даты. По умолчанию этой начальной датой считается 1 января 1900 года.

А что же текущее время? Ещё интереснее — за точку отсчета каждых суток берется 00:00:00, которое представляется как 1. А дальше, эта единичка уменьшается, по мере того как уменьшается оставшееся в сутках время. Например 12.00 дня это с точки зрения MS Excel 0,5 (прошла половина суток), а 18.00 — 0,25 (прошли 3 четверти суток).

В итоге, дата 17 июня 2019 года, 12:30, «языком экселя» выглядит как 43633 (17.06.19) + 0,52 (12:30), то есть число 43633,52.

Как превратить число в текст? Поместите его в кавычки!

Классификация типов данных

Тип данных — это характеристика информации, хранимой на листе. На основе этой характеристики программа определяет, каким образом обрабатывать то или иное значение.

Типы данных делятся на две большие группы: константы и формулы. Отличие между ними состоит в том, что формулы выводят значение в ячейку, которое может изменяться в зависимости от того, как будут изменяться аргументы в других ячейках. Константы – это постоянные значения, которые не меняются.

В свою очередь константы делятся на пять групп:

  • Текст;
  • Числовые данные;
  • Дата и время;
  • Логические данные;
  • Ошибочные значения.

Текстовые значения

Текстовый тип содержит символьные данные и не рассматривается Excel, как объект математических вычислений. Это информация в первую очередь для пользователя, а не для программы. Текстом могут являться любые символы, включая цифры, если они соответствующим образом отформатированы. В языке DAX этот вид данных относится к строчным значениям. Максимальная длина текста составляет 268435456 символов в одной ячейке.

Для ввода символьного выражения нужно выделить ячейку текстового или общего формата, в которой оно будет храниться, и набрать текст с клавиатуры. Если длина текстового выражения выходит за визуальные границы ячейки, то оно накладывается поверх соседних, хотя физически продолжает храниться в исходной ячейке.

Дата и время

Ещё одним типом данных является формат времени и даты. Это как раз тот случай, когда типы данных и форматы совпадают. Он характеризуется тем, что с его помощью можно указывать на листе и проводить расчеты с датами и временем. Примечательно, что при вычислениях этот тип данных принимает сутки за единицу. Причем это касается не только дат, но и времени. Например, 12:30 рассматривается программой, как 0,52083 суток, а уже потом выводится в ячейку в привычном для пользователя виде.

Существует несколько видов форматирования для времени:

  • ч:мм:сс;
  • ч:мм;
  • ч:мм:сс AM/PM;
  • ч:мм AM/PM и др.

Аналогичная ситуация обстоит и с датами:

  • ДД.ММ.ГГГГ;
  • ДД.МММ
  • МММ.ГГ и др.

Есть и комбинированные форматы даты и времени, например ДД:ММ:ГГГГ ч:мм.

Также нужно учесть, что программа отображает как даты только значения, начиная с 01.01.1900.

Логические данные

Довольно интересным является тип логических данных. Он оперирует всего двумя значениями: «ИСТИНА» и «ЛОЖЬ». Если утрировать, то это означает «событие настало» и «событие не настало». Функции, обрабатывая содержимое ячеек, которые содержат логические данные, производят те или иные вычисления.

Разновидности типов данных

Выделяются две большие группы типов данных:

  • константы – неизменные значения;
  • формулы – значения, которые меняются в зависимости от изменения других.

В группу “константы” входят следующие типы данных:

  • числа;
  • текст;
  • дата и время;
  • логические данные;
  • ошибки.

Число

Этот тип данных применяется в различных расчетах. Как следует из названия, здесь предполагается работа с числами, и для которых может быть задан один из следующих форматов ячеек:

  • числовой;
  • денежный;
  • финансовый;
  • процентный;
  • дробный;
  • экспоненциальный.

Формат ячейки можно задать двумя способами:

  1. Во вкладке “Главная” в группе инструментов “Число” нажимаем по стрелке рядом с текущим значением и в раскрывшемся списке выбираем нужный вариант.
  2. В окне форматирования (вкладка “Число”), в которое можно попасть через контекстное меню ячейки.

Для каждого из форматов, перечисленных выше (за исключением дробного), можно задать количество знаков после запятой, а для числового – к тому же, включить разделитель групп разрядов.

Чтобы ввести значение в ячейку, достаточно просто выделить ее (с нужным форматом) и набрать с помощью клавиш на клавиатуре нужные символы (либо вставить ранее скопированные данные из буфера обмена). Или можно выделить ячейку, после чего ввести нужные символы в строке формул.

Также можно поступить наоборот – сначала ввести значение в нужной ячейке, а формат поменять после.

Текст

Данный тип данных не предназначен для выполнения расчетов и носит исключительно информационный характер. В качестве текстового значения могут использоваться любые знаки, цифры и т.д.

Ввод текстовой информации происходит таким же образом, как и числовой. Если текст не помещается в рамках выбранной ячейки, он будет перекрывать соседние (если они пустые).

Ошибки

В некоторых случаях пользователь может видеть в Excel ошибки, которые бывают следующих видов:

  • #ДЕЛ/О! – результат деления на число 0
  • #Н/Д – введены недопустимые данные;
  • #ЗНАЧ! – использование неправильного вида аргумента в функции;
  • #ЧИСЛО! – неверное числовое значение;
  • #ССЫЛКА! – удалена ячейка, на которую ссылалась формула;
  • #ИМЯ? – неправильное имя в формуле;
  • #ПУСТО! – неправильно указан адрес дапазона.

Подключение к внешним данным

Вы можете получить доступ к внешним источникам через вкладку Данные, группу Получить и преобразовать данные. Подключения к данным хранятся вместе с книгой, и вы можете просмотреть их, выбрав пункт Данные –> Запросы и подключения.

Подключение к данным может быть отключено на вашем компьютере. Для подключения данных пройдите по меню Файл –> Параметры –> Центр управления безопасностью –> Параметры центра управления безопасностью –> Внешнее содержимое. Установите переключатель на одну из опций: включить все подключения к данным (не рекомендуется) или запрос на подключение к данным.

Настройка доступа к внешним данным; чтобы увеличить изображение кликните на нем правой кнопкой мыши и выберите Открыть картинку в новой вкладке

Подробнее о подключении к внешним источникам данных см. Кен Пульс и Мигель Эскобар. Язык М для Power Query. При использовании таблиц, подключенных к данным можно переставлять и удалять столбцы, не изменяя запрос. Excel продолжает сопоставлять запрошенные данные с правильными столбцами. Однако ширина столбцов обычно автоматически устанавливается при обновлении. Чтобы запретить Excel автоматически устанавливать ширину столбцов Таблицы при обновлении, щелкните правой кнопкой мыши в любом месте Таблицы и пройдите по меню Конструктор –> Данные из внешней таблицы –> Свойства, а затем снимите флажок Задать ширину столбца.

Свойства Таблицы, подключенной к внешним данным

Подключение к базе данных

Для подключения к базе данных SQL Server выберите Данные –> Получить данные –> Из базы данных –> Из базы данных SQL Server. Появится мастер подключения к данным, предлагающий элементы управления для указания имени сервера и типа входа, который будет использоваться для открытия соединения. Обратитесь к своему администратору SQL Server или ИТ-администратору, чтобы узнать, как ввести учетные данные для входа.

Подключение к базе данных SQL Server

При импорте данных в книгу Excel их можно загрузить в модель данных, предоставив доступ к ним другим инструментам анализа, таким как Power Pivot.

Существует много различных типов доступных источников данных, и иногда шаблоны соединений по умолчанию, представленные Excel, не работают.

Импорт данных из базы данных Microsoft Access

Мы научимся импортировать данные из базы данных MS Access. Следуйте инструкциям ниже

Шаг 1 – Откройте новую пустую книгу в Excel.

Шаг 2 – Перейдите на вкладку ДАННЫЕ на ленте.

Шаг 3 – Нажмите « Доступ» в группе «Получить внешние данные». Откроется диалоговое окно « Выбор источника данных ».

Шаг 4 – Выберите файл базы данных Access, который вы хотите импортировать. Файлы базы данных Access будут иметь расширение .accdb.

Откроется диалоговое окно «Выбор таблицы», в котором отображаются таблицы, найденные в базе данных Access. Вы можете импортировать все таблицы в базе данных одновременно или импортировать только выбранные таблицы на основе ваших потребностей анализа данных.

Шаг 5 – Установите флажок Включить выбор нескольких таблиц и выберите все таблицы.

Шаг 6 – Нажмите ОК. Откроется диалоговое окно « Импорт данных ».

Как вы заметили, у вас есть следующие опции для просмотра данных, которые вы импортируете в свою рабочую книгу:

  • Таблица
  • Отчет сводной таблицы
  • PivotChart
  • Power View Report

У вас также есть возможность – только создать соединение . Далее отчет по сводной таблице выбран по умолчанию.

Excel также дает вам возможность поместить данные в вашу книгу –

  • Существующий лист
  • Новый лист

Вы найдете еще один флажок, который установлен и отключен. Добавьте эти данные в модель данных . Каждый раз, когда вы импортируете таблицы данных в свою книгу, они автоматически добавляются в модель данных в вашей книге. Вы узнаете больше о модели данных в следующих главах.

Вы можете попробовать каждый из вариантов, чтобы просмотреть импортируемые данные и проверить, как эти данные отображаются в вашей рабочей книге.

  • Если вы выберете « Таблица» , опция «Существующая рабочая таблица» будет отключена, будет выбрана опция « Новая рабочая таблица», и Excel создаст столько таблиц, сколько будет импортировано таблиц из базы данных. Таблицы Excel отображаются в этих таблицах.

  • Если вы выберете Отчет сводной таблицы , Excel импортирует таблицы в рабочую книгу и создаст пустую сводную таблицу для анализа данных в импортированных таблицах. У вас есть возможность создать сводную таблицу на существующем листе или новом листе.

    Таблицы Excel для импортированных таблиц данных не будут отображаться в книге. Однако вы найдете все таблицы данных в списке полей сводной таблицы вместе с полями в каждой таблице.

  • Если вы выберете PivotChart , Excel импортирует таблицы в рабочую книгу и создаст пустую PivotChart для отображения данных в импортированных таблицах. У вас есть возможность создать сводную диаграмму на существующем или новом листе.

    Таблицы Excel для импортированных таблиц данных не будут отображаться в книге. Однако вы найдете все таблицы данных в списке полей PivotChart вместе с полями в каждой таблице.

  • Если вы выберите Power View Report , Excel импортирует таблицы в рабочую книгу и создаст Power View Report в новой рабочей таблице. В последующих главах вы узнаете, как использовать отчеты Power View для анализа данных.

    Таблицы Excel для импортированных таблиц данных не будут отображаться в книге. Однако вы найдете все таблицы данных в списке полей Power View Report вместе с полями в каждой таблице.

  • Если вы выберете опцию – Только создать соединение , между базой данных и вашей книгой будет установлено соединение для передачи данных. Таблицы или отчеты не отображаются в книге. Однако импортированные таблицы по умолчанию добавляются в модель данных в вашей книге.

    Вам необходимо выбрать любой из этих параметров в зависимости от вашего намерения импортировать данные для анализа данных. Как вы заметили выше, независимо от выбранной вами опции, данные импортируются и добавляются в модель данных в вашей рабочей книге.

Если вы выберете « Таблица» , опция «Существующая рабочая таблица» будет отключена, будет выбрана опция « Новая рабочая таблица», и Excel создаст столько таблиц, сколько будет импортировано таблиц из базы данных. Таблицы Excel отображаются в этих таблицах.

Если вы выберете Отчет сводной таблицы , Excel импортирует таблицы в рабочую книгу и создаст пустую сводную таблицу для анализа данных в импортированных таблицах. У вас есть возможность создать сводную таблицу на существующем листе или новом листе.

Таблицы Excel для импортированных таблиц данных не будут отображаться в книге. Однако вы найдете все таблицы данных в списке полей сводной таблицы вместе с полями в каждой таблице.

Если вы выберете PivotChart , Excel импортирует таблицы в рабочую книгу и создаст пустую PivotChart для отображения данных в импортированных таблицах. У вас есть возможность создать сводную диаграмму на существующем или новом листе.

Таблицы Excel для импортированных таблиц данных не будут отображаться в книге. Однако вы найдете все таблицы данных в списке полей PivotChart вместе с полями в каждой таблице.

Если вы выберите Power View Report , Excel импортирует таблицы в рабочую книгу и создаст Power View Report в новой рабочей таблице. В последующих главах вы узнаете, как использовать отчеты Power View для анализа данных.

Таблицы Excel для импортированных таблиц данных не будут отображаться в книге. Однако вы найдете все таблицы данных в списке полей Power View Report вместе с полями в каждой таблице.

Если вы выберете опцию – Только создать соединение , между базой данных и вашей книгой будет установлено соединение для передачи данных. Таблицы или отчеты не отображаются в книге. Однако импортированные таблицы по умолчанию добавляются в модель данных в вашей книге.

Вам необходимо выбрать любой из этих параметров в зависимости от вашего намерения импортировать данные для анализа данных. Как вы заметили выше, независимо от выбранной вами опции, данные импортируются и добавляются в модель данных в вашей рабочей книге.

Импорт данных с веб-страницы

Иногда вам может понадобиться использовать данные, которые обновляются на веб-сайте. Вы можете импортировать данные из таблицы на веб-сайте в Excel.

Шаг 1 – Откройте новую пустую книгу в Excel.

Шаг 2 – Перейдите на вкладку ДАННЫЕ на ленте.

Шаг 3 – Нажмите « Из Интернета» в группе « Получить внешние данные ». Откроется диалоговое окно « Новый веб-запрос ».

Шаг 4 – Введите URL-адрес веб-сайта, с которого вы хотите импортировать данные, в поле рядом с адресом и нажмите «Перейти».

Шаг 5 – Данные на сайте появляются. Рядом с данными таблицы будут отображаться желтые значки со стрелками, которые можно импортировать.

Шаг 6 – Нажмите желтые значки, чтобы выбрать данные, которые вы хотите импортировать. Это превращает желтые значки в зеленые поля с галочкой, как показано на следующем снимке экрана.

Шаг 7 – Нажмите кнопку «Импорт» после того, как вы выбрали то, что вы хотите.

Откроется диалоговое окно « Импорт данных ».

Шаг 8 – Укажите, куда вы хотите поместить данные и нажмите Ok.

Шаг 9 – Организовать данные для дальнейшего анализа и / или представления.

Копировать-вставить данные из Интернета

Другой способ получения данных с веб-страницы – копирование и вставка необходимых данных.

Шаг 1 – Вставьте новый лист.

Шаг 2 – Скопируйте данные с веб-страницы и вставьте их на лист.

Шаг 3 – Создайте таблицу с вставленными данными.

Импорт данных из текстового файла

Если у вас есть данные в файлах .txt или .csv или .prn , вы можете импортировать данные из этих файлов, рассматривая их как текстовые файлы. Следуйте инструкциям ниже

Шаг 1 – Откройте новый лист в Excel.

Шаг 2 – Перейдите на вкладку ДАННЫЕ на ленте.

Шаг 3 – Нажмите « Из текста» в группе «Получить внешние данные». Откроется диалоговое окно « Импорт текстового файла ».

Вы можете видеть, что текстовые файлы с расширениями .prn, .txt и .csv принимаются.

Шаг 4 – Выберите файл. Имя выбранного файла появится в поле Имя файла. Кнопка «Открыть» изменится на кнопку «Импорт».

Шаг 5 – Нажмите кнопку «Импорт». Мастер импорта текста – появляется диалоговое окно « Шаг 1 из 3 ».

Шаг 6 – Выберите опцию «С разделителями», чтобы выбрать тип файла, и нажмите «Далее».

Откроется мастер импорта текста – шаг 2 из 3 .

Шаг 7 – В разделе «Разделители» выберите « Другое» .

Шаг 8 – В поле рядом с Другой введите | (Это разделитель в текстовом файле, который вы импортируете).

Шаг 9 – Нажмите Далее.

Откроется мастер импорта текста – шаг 3 из 3 .

Шаг 10 – В этом диалоговом окне вы можете установить формат данных столбца для каждого из столбцов.

Шаг 11. После завершения форматирования данных столбцов нажмите кнопку «Готово». Откроется диалоговое окно « Импорт данных ».

Вы увидите следующее –

  • Таблица выбрана для просмотра и отображается серым цветом. Таблица – единственный вариант просмотра, который у вас есть в этом случае.

  • Вы можете поместить данные либо в существующий рабочий лист, либо в новый рабочий лист.

  • Вы можете установить или не устанавливать флажок Добавить эти данные в модель данных.

  • Нажмите OK после того, как вы сделали выбор.

Таблица выбрана для просмотра и отображается серым цветом. Таблица – единственный вариант просмотра, который у вас есть в этом случае.

Вы можете поместить данные либо в существующий рабочий лист, либо в новый рабочий лист.

Вы можете установить или не устанавливать флажок Добавить эти данные в модель данных.

Нажмите OK после того, как вы сделали выбор.

Данные появятся на указанном вами листе. Вы импортировали данные из текстового файла в книгу Excel.

Импорт данных из другой книги

Возможно, вам придется использовать данные из другой книги Excel для анализа данных, но кто-то другой может поддерживать другую книгу.

Чтобы получать последние данные из другой книги, установите соединение данных с этой книгой.

Шаг 1 – Нажмите DATA> Соединения в группе Соединения на ленте.

Откроется диалоговое окно « Подключения к книге».

Шаг 2. Нажмите кнопку «Добавить» в диалоговом окне «Подключения к книге». Откроется диалоговое окно « Существующие подключения ».

Шаг 3 – Нажмите кнопку Обзор для более … Откроется диалоговое окно « Выбор источника данных ».

Шаг 4 – Нажмите кнопку « Новый источник» . Откроется диалоговое окно мастера подключения к данным .

Шаг 5 – Выберите Other / Advanced в списке источников данных и нажмите Next. Откроется диалоговое окно «Свойства ссылки на данные».

Шаг 6 – Установите свойства канала передачи данных следующим образом –

  • Перейдите на вкладку « Соединение ».

  • Нажмите Использовать имя источника данных.

  • Нажмите стрелку вниз и выберите « Файлы Excel» в раскрывающемся списке.

  • Нажмите ОК.

Перейдите на вкладку « Соединение ».

Нажмите Использовать имя источника данных.

Нажмите стрелку вниз и выберите « Файлы Excel» в раскрывающемся списке.

Нажмите ОК.

Откроется диалоговое окно « Выбрать рабочую книгу ».

Шаг 7 – Найдите место, где у вас есть рабочая книга для импорта. Нажмите ОК.

Откроется диалоговое окно « Мастер подключения к данным » с выбором базы данных и таблицы.

Примечание. В этом случае Excel обрабатывает каждый рабочий лист, который импортируется, как таблицу. Имя таблицы будет именем рабочего листа. Таким образом, чтобы иметь значимые имена таблиц, назовите / переименуйте рабочие листы в зависимости от ситуации.

Шаг 8 – Нажмите Далее. Откроется диалоговое окно мастера подключения к данным с сохранением файла подключения к данным и завершением.

Шаг 9 – Нажмите кнопку Готово. Откроется диалоговое окно « Выбор таблицы ».

Как вы заметили, Name – это имя листа, которое импортируется как тип TABLE. Нажмите ОК.

Соединение данных с выбранной вами рабочей книгой будет установлено.

Импорт данных из других источников

Excel предоставляет вам возможность выбора различных других источников данных. Вы можете импортировать данные из них в несколько шагов.

Шаг 1 – Откройте новую пустую книгу в Excel.

Шаг 2 – Перейдите на вкладку ДАННЫЕ на ленте.

Шаг 3 – Нажмите Из других источников в группе Получить внешние данные.

Появляется выпадающий список с различными источниками данных.

Вы можете импортировать данные из любого из этих источников данных в Excel.

Задача для получения данных в Excel

И для того чтобы более понятно рассмотреть данную возможность, мы это будем делать как обычно на примере. Другими словами допустим, что нам надо выгрузить данные, одной таблицы, из базы SQL сервера, средствами Excel, т.е. без помощи вспомогательных инструментов, таких как Management Studio SQL сервера.

Примечание! Все действия мы будем делать, используя Excel 2010. SQL сервер у нас будет MS Sql 2008.

И для начала разберем исходные данные, допустим, есть база test, а в ней таблица test_table, данные которой нам нужно получить, для примера будут следующими:

Эти данные располагаются в таблице test_table базы test, их я получил с помощью простого SQL запроса select, который я выполнил в окне запросов Management Studio. И если Вы программист SQL сервера, то Вы можете выгрузить эти данные в Excel путем простого копирования (данные не большие), или используя средство импорта и экспорта MS Sql 2008.

Источники

  • https://public-pc.com/podklyuchenie-vneshnih-dannyh-v-excel/
  • https://exceltable.com/funkcii-excel/vyborka-iz-bazy-dannyh-bizvlech
  • http://bussoft.ru/tablichnyiy-redaktor-excel/tipy-dannyh-v-redaktore-elektronnyh-tablicz-ms-excel.html
  • https://lumpics.ru/data-types-in-excel/
  • https://MicroExcel.ru/tipy-dannyh/
  • https://baguzin.ru/wp/glava-8-rabota-s-vneshnimi-dannymi-v-tablitsah-excel/
  • https://coderlessons.com/tutorials/bolshie-dannye-i-analitika/izuchite-analiz-dannykh-excel/import-dannykh-v-excel
  • https://info-comp.ru/obucheniest/375-excel-get-data-from-sql-server.html

Part II. Advanced VBA Techniques

Chapter 11. Working with External Data and Files

In This Chapter

· Working with external data connections

· Using ActiveX data objects to get external data

· Performing common file operations

· Working with text files

Working with External Data Connections

External data is exactly what it sounds like: data that isn’t located in the Excel workbook in which you’re operating. Some examples of external data sources are text files, Access tables, SQL Server tables, and even other Excel workbooks.

There are numerous ways to get data into Excel. In fact, between the functionality found in the UI and the VBA/code techniques, there are too many techniques to focus on in one chapter. Instead, then, in this chapter we’ll focus on a handful of techniques that can be implemented in most situations and don’t come with a lot of pitfalls and gotchas.

The first of those techniques is to use an external data connection.

Manually creating a connection

Excel has made it easy to manually connect to external data sources such as Microsoft Access, SQL Server, or any other ODBC connection you regularly use. For example, you can connect to an Access database by following these steps:

inline On the Web

Feel free to follow along by using the Facility Services.accdb Access database found on this book’s website. The DynamicDataConnection.xlsm file contains the sample macros found in this section.

1. Open a new Excel workbook and click the Data tab on the Ribbon.

2. In the Get External Data group, select the From Access icon.

The Select Data Source dialog box opens, as shown in Figure 11.1. If the database from which you want to import data is local, browse to the file’s location and select it. If your target Access database resides on a network drive at another location, you need the proper authorization to select it.

3. Navigate to your sample database and click Open.

In some environments, a series of Data Link Properties dialog boxes opens asking for credentials (username and password). Most Access databases don’t require logon credentials, but if your database does require a username and password, type them in the Data Link Properties dialog box.

4. Click OK. The Select Table dialog box shown in Figure 11.2 opens. This dialog box lists all the available tables and queries in the selected database.

inline Tip

The Select Table dialog box contains a column called Type. There are two types of Access objects you can work with: views and tables. VIEW indicates that the dataset listed is an Access query, and TABLE indicates that the dataset is an Access table. In this example, Sales_By_Employee is actually an Access query. This means that you import the results of the query. This is true interaction at work; Access does all the back-end data management and aggregation, and Excel handles the analysis and presentation!

5. Select your target table or query and click OK.

The Import Data dialog box shown in Figure 11.3 opens. Here you define where and how to import the table. You have the option of importing the data into a Table, a PivotTable Report, a PivotChart, or a Power View Report. You also have the option of creating only the connection, making the connection available for later use.

Note that if you choose PivotChart or PivotTable Report, the data is saved to a pivot cache without writing the actual data to the worksheet. Thus your pivot table can function as normal without you having to import potentially hundreds of thousands of data rows twice (once for the pivot cache and once for the spreadsheet).

6. Select Table as the output view and define cell A1 as the output location, as shown in Figure 11.3.

7. Click OK.

Screenshot shows Documents Library page which selects file name as Facility Services.accdb.

Figure 11.1 Choose the source database that contains the data you want imported.

Screenshot shows Select Table page which displays Name, Description, Date modified, Created and Type which selects Sales_By_Employees under the Name category and OK button.

Figure 11.2 Select the Access object you want to import.

Screenshot shows Import Data page on the excel sheet which selects Table, Existing worksheet and OK button.

Figure 11.3 Choosing how and where to view your Access data.

Your reward for all your work is a table that contains the imported data from your Access database, as shown in Figure 11.4.

Excel sheet shows data's entered for Region, Market, Branch_Number, Employee_Number et cetera.

Figure 11.4 Data imported from Access.

The incredibly powerful thing about importing data this way is that it’s refreshable. That’s right. If you import data from Access using this technique, Excel creates a table that you can update by right-clicking it and selecting Refresh from the pop-up menu, as shown in Figure 11.5. When you update your imported data, Excel reconnects to your Access database and imports the data again. As long as a connection to your database is available, you can refresh with a mere click of the mouse.

Image described by surrounding text.

Figure 11.5 As long as a connection to your database is available, you can update your table with the latest data.

Again, a major advantage to using the Get External Data group is that you can establish a refreshable data connection between Excel and Access. In most cases, you can set up the connection one time and then just update the data connection when needed. You can even record an Excel macro to update the data on some trigger or event, which is ideal for automating the transfer of data from Access.

Manually editing data connections

Once you have a connection, you can use the connection properties to write your own SQL statements. This gives you more control over the data you pull into your Excel model and allows you to perform advanced actions like running SQL Server stored procedures.

Go to the Data tab on the Ribbon and select Connections. This will activate the Workbook Connections dialog box shown in Figure 11.6. Choose the connection you want to edit and then click on the Properties button.

Image described by surrounding text.

Figure 11.6 Choose the Properties button for the connection you want to change.

The Connection Properties dialog box will open. Here, you can click on the Definition tab (see Figure 11.7). Change the Command Type property to SQL, and then enter your SQL statement.

Screenshot shows Connection Properties page which selects SQL for Command type under Definition. Finally, OK button is chosen.

Figure 11.7 On the Definition tab, select the SQL command type and enter your SQL Statement.

Using VBA to create dynamic connections

You may have noticed that the last few examples have hard-coded the criteria in the SQL statements. For example, in Figure 11.7, Tulsa is specified directly into the SQL statement WHERE clause. This obviously would cause the data being returned to always be data for Tulsa.

But what if you wanted to select a market and have the SQL statement dynamically change to respond to your selection? Well, you can use a bit of VBA to change the SQL statement on the fly. Follow these steps:

1. Designate a cell in your worksheet that will catch the dynamic selection for your criteria. For example, in Figure 11.8, cell C2 will be the place that users can select a market. You typically give users a way to select criteria with either a Combo Box or a Data Validation list.

2. Open the Workbook Connections dialog box by clicking the Connections command on the Data tab. Take note of the name for the connection you want to dynamically change. In Figure 11.9, you see the connection name is Facility Services.

3. Close the Workbook Connections dialog box and press Alt+F11 on your keyboard. This will take you to the Visual Basic Editor.

4. In the Visual Basic Editor, select Insert ➜ Module from the menu bar.

5. Enter the following code in the newly created module:

6. Sub RefreshQuery()

7.

8. ActiveWorkbook.Connections( _

9. «Facility Services»).OLEDBConnection.CommandText = _

10. «SELECT * FROM [Sales_By_Employee] WHERE [Market] = ‘» & _

11. Range(«C2″).Value &»‘»

12.

13. ActiveWorkbook.Connections(«Facility Services»).Refresh

14.

15. End Sub

This code creates a new macro called RefreshQuery. This macro uses the Workbook .Connections collection to change the attributes of the specified connection. In this case, you want to change the CommandText property of the FacilityServices connection.

The command text is essentially the SQL Statement you want the connection to use when connecting to the data source. In this example, the Command Text selects from the [Sales_By_Employee] table and sets the criteria for the [Market] field to the value in cell C2. The code then refreshes the Facility Services connection.

16.Close the Visual Basic Editor and place a new command button on your worksheet. To do this, click on the Developer tab, select the Insert dropdown, and add a Button Form control.

17.Assign the newly created RefreshQuery macro to the command button.

Image described by surrounding text.

Figure 11.8 Designate a cell that will trap the criteria selection.

Image described by surrounding text.

Figure 11.9 Take note of the connection name (Facility Services in this example).

If all went smoothly, you will have a nifty mechanism that allows for the dynamic extraction of data from your external database based on the criteria you specified (See Figure 11.10).

Screenshot shows data's entered for Region, Market, Branch_Number, Employee_Number, Last_Name on an excel sheet and selects DENVER under Market category and choses Get Data.

Figure 11.10 You now have an easy-to-use mechanism for pulling external data for a specified market.

Iterating through all connections in a workbook

You can also use the Workbook.Connections collection to iterate through all the connection objects in a workbook and examine or modify their properties. For instance, the following macro populates a worksheet with a list of all connection objects in the current workbook, along with their associated connection strings and command texts:

Sub ListConnections()

Dim i As Long

Dim Cn As WorkbookConnection

Worksheets.Add

With ActiveSheet.Range(«A1:C1»)

.Value = Array(«Cn Name»,»Connection String»,»Command Text»)

.EntireColumn.AutoFit

End With

For Each Cn In ThisWorkbook.Connections

i = i + 1

Select Case Cn.Type

Case Is = xlConnectionTypeODBC

With ActiveSheet

.Range(«A1»).Offset(i, 0).Value = Cn.Name

.Range(«A1»).Offset(i, 1).Value = Cn.ODBCConnection.Connection

.Range(«A1»).Offset(i, 2).Value = Cn.ODBCConnection.CommandText

End With

Case Is = xlConnectionTypeOLEDB

With ActiveSheet

.Range(«A1»).Offset(i, 0).Value = Cn.Name

.Range(«A1»).Offset(i, 1).Value = Cn.OLEDBConnection.Connection

.Range(«A1»).Offset(i, 2).Value = Cn.OLEDBConnection.CommandText

End With

End Select

Next Cn

End Sub

Using ADO and VBA to Pull External Data

Another technique for working with external data is to use VBA with ADO (ActiveX Data Objects). Using the combination of ADO with VBA will allow you to work with external data sets in memory. This comes in handy when you need to perform complex, multi-layered procedures and checks on external data sets, but you don’t want to create workbook connections or return those external data sets to the workbook.

inline Note

When working with complex Excel workbooks that pull data from external sources, you will periodically encounter code (written by others) that utilizes ADO. It’s important you recognize and understand the basics of ADO so you can deal with this kind of code. The next few sections will walk you through some of the fundamental concepts of ADO and will show you how to construct your own ADO procedures to pull data. Keep in mind that ADO programming is a broad topic that cannot be fully covered here. If you find that you need to work extensively with ADO and external data in your Excel application, you’ll probably want to invest in one or more books that cover this topic in detail.

When trying to grasp the basics of ADO, it helps to think of ADO as a tool that will help you accomplish two tasks: connect to a data source and specify the dataset with which to work. In the following section, you will explore the fundamental syntax you will need to know in order to do just that.

The connection string

The first thing you must do is connect to a data source. In order to do this, you must give VBA a few pieces of information. This information is passed to VBA in the form of a connection string. Here is an example connection string that points to an Access database.

«Provider=Microsoft.ACE.OLEDB.12.0;» & _

«Data Source= C:MyDatabase.accdb;» & _

«User ID=Administrator;» & _

«Password=AdminPassword»

Don’t be intimidated by all the syntax here. A connection string is fundamentally nothing more than a text string that holds a series of variables (also called arguments), which VBA uses to identify and open a connection to a data source. Although connection strings can get pretty fancy with a myriad of arguments and options, there are a handful of arguments that are commonly used when connecting to either Access or Excel.

For novices of ADO, it helps to focus on these commonly used arguments when working with connection strings: Provider, Data Source, Extended Properties, User ID, and Password:

· Provider: The Provider argument tells VBA what type of data source with which you are working. When using Access or Excel as the data source, the Provider syntax will read: Provider=Microsoft.ACE.OLEDB.12.0.

· Data Source: The Data Source argument tells VBA where to find the database or workbook that contains the data needed. With the Data Source argument, you will pass the full path of the database or workbook. For example: Data Source=C:MydirectoryMyDatabaseName.accdb.

· Extended Properties: The Extended Properties argument is typically used when connecting to an Excel workbook. This argument tells VBA that the data source is something other than a database. When working with an Excel workbook, this argument reads:Extended Properties=Excel 12.0.

· User ID: The User ID argument is optional and only used if a user id is required to connect to the data source: User Id=MyUserId.

· Password: The Password argument is optional and only used if a password is required to connect to the data source: Password=MyPassword.

Take a moment now to examine a few examples of how these arguments are used in different connection strings.

· Connecting to an Access database:

·»Provider=Microsoft.ACE.OLEDB.12.0;» & _

·»Data Source= C:MyDatabase.accdb»

· Connecting to an Access database with Password and User ID:

·

·»Provider=Microsoft.ACE.OLEDB.12.0;» & _

·»Data Source= C:MyDatabase.accdb;» & _

·»User ID=Administrator;» & _

·»Password=AdminPassword»

· Connecting to an Excel workbook:

·»Provider=Microsoft.ACE.OLEDB.12.0;» & _

·»Data Source=C:MyExcelWorkbook.xlsx;» & _

·»Extended Properties=Excel 12.0″

Declaring a Recordset

In addition to building a connection to your data source, you will need to define the data set with which you need to work. In ADO, this dataset is referred to as the Recordset. A Recordset object is essentially a container for the records and fields returned from the data source. The most common way to define a Recordset is to open an existing table or query using the following arguments:

Recordset.Open Source, ConnectString, CursorType, LockType

The Source argument specifies the data that is to be extracted. This is typically a table, a query, or a SQL statement that retrieves records. The ConnectString argument specifies the connection string used to connect to your chosen data source. The CursorType argument defines how a Recordset allows you to move through the data to be extracted. The CursorTypes that are commonly used are:

· adOpenForwardOnly: This is the default setting; if you don’t specify a CursorType, the Recordset will automatically be adOpenForwardOnly. This CursorType is the most efficient type because it only allows you to move through the Recordset one way: from beginning to end. This is ideal for reporting processes where data only needs to be retrieved and not traversed. Keep in mind that you cannot make changes to data when using this CursorType.

· adOpenDynamic: This CursorType is typically used in processes where there is a need for looping, moving up and down through the dataset, or the ability to dynamically see any edits made to the dataset. This CursorType is typically memory- and resource-intensive and should be used only when needed.

· adOpenStatic: This CursorType is ideal for the quick return of results as it essentially returns a snapshot of your data. However, this is different from the adOpenForwardOnly CursorType as it allows you to navigate the returned records. In addition, when using this CursorType, the data returned can be made updateable by setting its LockType to something other than adLockReadOnly.

The LockType argument lets you specify whether the data returned by the Recordset can be changed. This argument is typically set to adLockReadOnly (the default setting) to indicate that there is no need to edit the data returned. Alternatively, you can set this argument to adLockOptimistic which allows for the free editing of the data returned.

Referencing the ADO object library

With these basic ADO fundamentals under your belt, you’re ready to create your own ADO procedure. But before you do anything with ADO, you need to first set a reference to the ADO object library. Just as each Microsoft Office application has its own set of objects, properties, and methods, so does ADO. Since Excel does not inherently know the ADO object model, you will need to point Excel to the ADO reference library.

Start by opening a new Excel workbook and opening the Visual Basic Editor.

Once you are in the Visual Basic Editor, go up to the application menu and select Tools ➜ References. This will open the References dialog box illustrated here in Figure 11.11. Scroll down until you locate the latest version of the Microsoft ActiveX Data Objects Library. Place a checkmark beside this entry and click OK.

Image described by surrounding text.

Figure 11.11 Select the latest version of the Microsoft ActiveX Data Objects Library.

inline Note

It is normal to have several versions of the same library displayed in the References dialog box. It’s generally best to select the latest version available. Note that versions after 2.8 are called Microsoft ActiveX Data Objects Recordset Library.

After you click the OK button, you can open the References dialog box again to ensure that your reference is set. You will know that your selection took effect when the Microsoft ActiveX Data Objects Library is displayed at the top of the Reference dialog box with a check next to it.

inline Note

Keep in mind that the references you set in any given workbook or database are not applied at the application level. This means that you will need to repeat these steps with each new workbook or database you create.

Putting it all together in code

Now that you understand a few of the basics of ADO, take a look at how they come together in VBA. The following example code uses ADO to connect to an Access database and retrieve the Products table.

Sub GetAccessData()

Dim MyConnect As String

Dim MyRecordset As ADODB.Recordset

MyConnect =»Provider=Microsoft.ACE.OLEDB.12.0;» & _

«Data Source= C:MyDirMyDatabaseName.accdb»

Set MyRecordset = New ADODB.Recordset

MyRecordset.Open»Products», _

MyConnect, adOpenStatic, adLockReadOnly

Sheets(«MySheetName»).Range(«A2»).CopyFromRecordset _

MyRecordset

With ActiveSheet.Range(«A1:C1»)

.Value = Array(«Product»,»Description»,»Segment»)

.EntireColumn.AutoFit

End With

End Sub

Now take a moment to understand what this macro is doing.

You first declare two variables: a string variable to hold the connection string and a Recordset object to hold the results of the data pull. In this example, the variable called MyConnect will hold the connection string identifying the data source. Meanwhile, the variable called MyRecordset will hold the data that is returned by the procedure.

Next, you define the connection string for the ADO procedure. In this scenario, you are connecting to the MyDatabaseName.accdb file found in the C:MyDir directory. Once you have defined the data source, you can open the Recordset and use MyConnect to return static read-only data.

Now you can use Excel’s CopyFromRecordset method to get the data out of the RecordSet and into the spreadsheet. This method requires two pieces of information: the location of the data output and the Recordset object that holds the data. In this example, you are copying the data in the MyRecordset object onto the sheet called MySheetName (starting at cell A2).

Interestingly enough, the CopyFromRecordset method does not return column headers or field names. This forces one final action where you add column headers by simply defining them in an array and writing them to the active sheet.

With ADO and VBA, you can build all the necessary components one time in a nicely packaged macro and then simply forget about it. As long as the defined variables in your code (i.e. the data source path, the Recordset, the output path) do not change, then your ADO-based procedures will require virtually zero maintenance.

Using ADO with the active workbook

There are countless ways you can use the fundamentals you have learned in this chapter. Of course, it would be impossible to go through every possibility here. However, there are some common scenarios where VBA can greatly enhance integration between Excel and Access.

Querying data from an Excel workbook

You can use an Excel workbook as a data source for your ADO procedures. To do so, you simply build an SQL statement that references the data within the Excel workbook. The idea is to pinpoint the dataset in Excel to query by passing either a sheet name, a range of cells, or a named range to the SQL statement.

To query all of the data on a specific worksheet, you pass the name of that worksheet followed by the dollar sign ($) as the table name in your SQL statement. Be sure to encapsulate the worksheet name with square brackets. For example:

SELECT * FROM [MySheet$]

If the worksheet name contains spaces or characters that are not alphanumeric, you need to wrap the worksheet name in single quotes. For instance:

Select * from [‘January Forecast vs. Budget$’]

To query a range of cells within a given worksheet, you first identify the sheet as described above and then add the target range. For example:

SELECT * FROM [MySheet$A1:G17]

To query a named range, simply use the name of the range as the table name in your SQL statement. For example:

SELECT * FROM MyNamedRange

In the following example, the entire used range in the SampleData worksheet is queried to return only those records that belong to the North Region.

Sub GetData_From_Excel_Sheet()

Dim MyConnect As String

Dim MyRecordset As ADODB.Recordset

Dim MySQL As String

MyConnect =»Provider=Microsoft.ACE.OLEDB.12.0;» & _

«Data Source=» & ThisWorkbook.FullName &»;» & _

«Extended Properties=Excel 12.0»

MySQL =» SELECT * FROM [SampleData$]» & _

» WHERE Region =’NORTH'»

Set MyRecordset = New ADODB.Recordset

MyRecordset.Open MySQL, MyConnect, adOpenStatic, adLockReadOnly

ThisWorkbook.Sheets.Add

ActiveSheet.Range(«A2»).CopyFromRecordset MyRecordset

With ActiveSheet.Range(«A1:F1»)

.Value = Array(«Region»,»Market»,»Branch_Number», _

«Invoice_Number»,»Sales_Amount»,»Contracted Hours»)

.EntireColumn.AutoFit

End With

End Sub

inline On the Web

A working example of this code is available on the book’s website in the workbook called QueryDataFromExcel.xlsm.

Appending records to an existing Excel table

There are often times when you don’t necessarily want to overwrite the data in your Excel worksheet when you bring in fresh data. Instead, you may want to simply add or append data to the existing table. In a typical scenario, you hard-code the location or range where you want a given recordset to be copied. In these situations, this location must dynamically change to reflect the first empty cell in your worksheet. The following example code demonstrates this technique.

Sub Append_Results()

Dim MyConnect As String

Dim MyRecordset As ADODB.Recordset

Dim MyRange As String

MyConnect =»Provider=Microsoft.ACE.OLEDB.12.0;» & _

«Data Source= C:MyDirMyDatabase.accdb»

Set MyRecordset = New ADODB.Recordset

MyRecordset.Open»Products», MyConnect, adOpenStatic

Sheets(«AppendData»).Select

MyRange =»A» & _

ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row + 1

ActiveSheet.Range(MyRange).CopyFromRecordset MyRecordset

End Sub

Because you want to append data to an existing table, you need to dynamically determine the first available empty cell that can be used as the output location for the data pull. The first step in accomplishing this goal is to find the first empty row. This is relatively easy to do thanks to Excel’s SpecialCells method.

Using the SpecialCells method, you can find the last used cell in the worksheet and then extract the row number of that cell. This gives you the last used row. To get the row number of the first empty row, you simply add 1; the next row down from the last used row will inherently be empty.

The idea is to concatenate the SpecialCells routine with a column letter (in this case “A”) to create a string that represents a range. For example, if the first empty row turns out to be 10, then the following code returns “A10.”

«A» & ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row + 1

Trapping this answer in the MyRange string variable allows you to pass the answer to the CopyFromRecordset.

Working with Text Files

VBA contains a number of statements that allow low-level manipulation of files. These input/output (I/O) statements give you much more control over files than Excel’s normal text file import and export options.

You can access a file in any of three ways:

· Sequential access: By far the most common method. This type allows reading and writing individual characters or entire lines of data.

· Random access: Used only if you’re programming a database application, which is not often done using VBA.

· Binary access: Used to read or write to any byte position in a file, such as when storing or displaying a bitmap image. This access method is rarely used in VBA.

Because random and binary access files are rarely used with VBA, this chapter focuses on sequential access files. In sequential access, your code starts reading from the beginning of the file and reads each line sequentially. For output, your code writes data to the end of the file.

inline Note

The method of reading and writing text files discussed in this book is the traditional data-channel approach. Another option is to use the object approach. The FileSystemObject object contains a TextStream object that can be used to read and write text files. The FileSystemObject object is part of Windows Scripting Host, which is disabled on some systems because of the malware potential associated with it.

Opening a text file

The VBA Open statement (not to be confused with the Open method of the Workbooks object) opens a file for reading or writing. Before you can read from or write to a file, you must open it.

The Open statement is versatile and has a complex syntax:

Open pathname For mode [Access access] [lock] _

As [#]filenumber [Len=reclength]

· pathname: Required. The pathname part of the Open statement is straightforward. It simply contains the name and path (optional) of the file to be opened.

· mode: Required. The file mode must be one of the following:

· Append: A sequential access mode that either allows the file to be read or allows data to be appended to the end of the file.

· Input: A sequential access mode that allows the file to be read but not written to.

· Output: A sequential access mode that allows the file to be read or written to. In this mode, a new file is always created. (An existing file with the same name is deleted.)

· Binary: A random access mode that allows data to be read or written to on a byte-by-byte basis.

· Random: A random access mode that allows data to be read or written in units determined by the reclength argument of the Open statement.

· access: Optional. The access argument determines what can be done with the file. It can be Read, Write, or Read Write.

· lock: Optional. The lock argument is useful for multiuser situations. The options are Shared, Lock Read, Lock Write, and Lock Read Write.

· filenumber: Required. A file number ranging from 1 to 511. You can use the FreeFile function to get the next available file number. (Read about FreeFile in the upcoming section, “Getting a file number.”)

· reclength: Optional. The record length (for random access files) or the buffer size (for sequential access files).

Reading a text file

The basic procedure for reading a text file with VBA consists of the following steps:

1. Open the file by using the Open statement.

2. Specify the position in the file by using the Seek function (optional).

3. Read data from the file by using the Input, Input #, or Line Input # statement.

4. Close the file by using the Close statement.

Writing a text file

The basic procedure for writing a text file is as follows:

1. Open or create the file by using the Open statement.

2. Optional. Specify the position in the file by using the Seek function.

3. Write data to the file by using the Write # or Print # statement.

4. Close the file by using the Close statement.

Getting a file number

Most VBA programmers simply designate a file number in their Open statement. For example:

Open»myfile.txt» For Input As #1

Then you can refer to the file in subsequent statements as #1.

If a second file is opened while the first is still open, you’d designate the second file as #2:

Open»another.txt» For Input As #2

Another approach is to use the VBA FreeFile function to get a file handle. Then you can refer to the file by using a variable. Here’s an example:

FileHandle = FreeFile

Open»myfile.txt» For Input As FileHandle

Determining or setting the file position

For sequential file access, you rarely need to know the current location in the file. If for some reason you need to know this information, you can use the Seek function.

inline Excel’s text file import and export features

Excel can directly read and write three types of text files:

· CSV (comma-separated value) files: Columns of data are separated by a comma, and each row of data ends in a carriage return character. For some non-English versions of Excel, a semicolon rather than a comma is used.

· PRN: Columns of data are aligned by character position, and each row of data ends in a carriage return. These files are also known as fixed-width files.

· TXT (Tab-delimited) files: Columns of data are separated by tab characters, and each row of data ends in a carriage return.

When you attempt to open a text file with the File ➜ Open command, the Text Import Wizard might appear to help you delineate the columns. If the text file is tab-delimited or comma-delimited, Excel usually opens the file without displaying the Text Import Wizard. If the data isn’t interpreted correctly, close the file and try renaming it to use a .txt extension.

The Text to Columns Wizard (accessed by choosing Data ➜ Data Tools ➜ Text to Columns) is identical to the Text Import Wizard but works with data stored in a single worksheet column.

Statements for reading and writing

VBA provides several statements to read and write data to a file.

Three statements are used for reading data from a sequential access file:

· Input: Reads a specified number of characters from a file.

· Input #: Reads data as a series of variables, with variables separated by a comma.

· Line Input #: Reads a complete line of data (delineated by a carriage return character, a linefeed character, or both).

Two statements are used for writing data to a sequential access file:

· Write #: Writes a series of values, with each value separated by a comma and enclosed in quotes. If you end the statement with a semicolon, a carriage return/linefeed sequence is not inserted after each value. Data written with Write # is usually read from a file with an Input # statement.

· Print #: Writes a series of values, with each value separated by a tab character. If you end the statement with a semicolon, a carriage return/linefeed sequence isn’t inserted after each value. Data written with Print # is usually read from a file with a Line Input # or an Input statement.

Text File Manipulation Examples

This section contains a number of examples that demonstrate various techniques that manipulate text files.

Importing data in a text file

The code in the following example reads a text file and then places each line of data in a single cell (beginning with the active cell):

Sub ImportData()

Open»c:datatextfile.txt» For Input As #1

r = 0

Do Until EOF(1)

Line Input #1, data

ActiveCell.Offset(r, 0) = data

r = r + 1

Loop

Close #1

End Sub

In most cases, this procedure won’t be very useful because each line of data is simply dumped into a single cell. It is easier to just open the text file directly by using File ➜ Open.

Exporting a range to a text file

The example in this section writes the data in a selected worksheet range to a CSV text file. Although Excel can export data to a CSV file, it exports the entire worksheet. This macro works with a specified range of cells.

Sub ExportRange()

Dim Filename As String

Dim NumRows As Long, NumCols As Integer

Dim r As Long, c As Integer

Dim Data

Dim ExpRng As Range

Set ExpRng = Selection

NumCols = ExpRng.Columns.Count

NumRows = ExpRng.Rows.Count

Filename = Application.DefaultFilePath &»textfile.csv»

Open Filename For Output As #1

For r = 1 To NumRows

For c = 1 To NumCols

Data = ExpRng.Cells(r, c).Value

If IsNumeric(Data) Then Data = Val(Data)

If IsEmpty(ExpRng.Cells(r, c)) Then Data =»»

If c <> NumCols Then

Write #1, Data;

Else

Write #1, Data

End If

Next c

Next r

Close #1

End Sub

Note that the procedure uses two Write # statements. The first statement ends with a semicolon, so a return/linefeed sequence isn’t written. For the last cell in a row, however, the second Write # statement doesn’t use a semicolon, which causes the next output to appear on a new line.

You used a variable named Data to store the contents of each cell. If the cell is numeric, the variable is converted to a value. This step ensures that numeric data won’t be stored with quotation marks. If a cell is empty, its Value property returns 0. Therefore, the code also checks for a blank cell (by using the IsEmpty function) and substitutes an empty string instead of a 0.

inline On the Web

These exporting and importing examples are available on the book’s website in the export and import csv.xlsm file.

Importing a text file to a range

The example in this section reads the CSV file created in the preceding example and then stores the values beginning at the active cell in the active worksheet. The code reads each character and essentially parses the line of data, ignoring quote characters and looking for commas to delineate the columns.

Sub ImportRange()

Dim ImpRng As Range

Dim Filename As String

Dim r As Long, c As Integer

Dim txt As String, Char As String * 1

Dim Data

Dim i As Integer

Set ImpRng = ActiveCell

On Error Resume Next

Filename = Application.DefaultFilePath &»textfile.csv»

Open Filename For Input As #1

If Err <> 0 Then

MsgBox»Not found:» & Filename, vbCritical,»ERROR»

Exit Sub

End If

r = 0

c = 0

txt =»»

Application.ScreenUpdating = False

Do Until EOF(1)

Line Input #1, Data

For i = 1 To Len(Data)

Char = Mid(Data, i, 1)

If Char =»,» Then ‘comma

ActiveCell.Offset(r, c) = txt

c = c + 1

txt =»»

ElseIf i = Len(Data) Then ‘end of line

If Char <> Chr(34) Then txt = txt & Char

ActiveCell.Offset(r, c) = txt

txt =»»

ElseIf Char <> Chr(34) Then

txt = txt & Char

End If

Next i

c = 0

r = r + 1

Loop

Close #1

Application.ScreenUpdating = True

End Sub

inline Note

The preceding procedure works with most data, but it has a flaw: It doesn’t handle data that contains a comma or a quote character. But commas resulting from formatting are handled correctly (they’re ignored). In addition, an imported date will be surrounded by number signs: for example, #2013-05-12#.

Logging Excel usage

The example in this section writes data to a text file every time Excel is opened and closed. For this example to work reliably, the procedure must be located in a workbook that’s opened every time you start Excel. Storing the macro in your Personal Macro Workbook is an excellent choice.

The following procedure, stored in the code module for the ThisWorkbook object, is executed when the file is opened:

Private Sub Workbook_Open()

Open Application.DefaultFilePath &»excelusage.txt» For Append As #1

Print #1,»Started» & Now

Close #1

End Sub

The procedure appends a new line to a file named excelusage.txt. The new line contains the current date and time and might look something like this:

Started 11/16/2013 9:27:43 PM

The following procedure is executed before the workbook is closed. It appends a new line that contains the word Stopped along with the current date and time.

Private Sub Workbook_BeforeClose(Cancel As Boolean)

Open Application.DefaultFilePath &»excelusage.txt» _

For Append As #1

Print #1,»Stopped» & Now

Close #1

End Sub

inline On the Web

A workbook that contains these procedures is available on the book’s website in the excel usage log.xlsm file.

inline Cross-Ref

Refer to Chapter 6 for more information about event-handler procedures such as Workbook_Open and Workbook_BeforeClose.

Filtering a text file

The example in this section demonstrates how to work with two text files at once. The FilterFile procedure that follows reads a text file (infile.txt) and copies only the rows that contain a specific text string («January») to a second text file (output.txt):

Sub FilterFile()

Open ThisWorkbook.Path &»infile.txt» For Input As #1

Open Application.DefaultFilePath &»output.txt» For Output As #2

TextToFind =»January»

Do Until EOF(1)

Line Input #1, data

If InStr(1, data, TextToFind) Then

Print #2, data

End If

Loop

Close ‘Close all files

End Sub

inline On the Web

This example, named filter text file.xlsm, is available on the book’s website.

Performing Common File Operations

Many applications that you develop for Excel require working with external files. For example, you might need to get a listing of files in a directory, delete files, or rename files. Excel can import and export several types of text files. In many cases, however, Excel’s built-in text file handling isn’t sufficient. For example, you might want to paste a list of filenames into a range or export a range of cells to a simple HyperText Markup Language (HTML) file.

In this chapter, you explore how to use Visual Basic for Applications (VBA) to perform common (and not so common) file operations and work directly with text files.

Excel provides two ways to perform common file operations:

· Use traditional VBA statements and functions: This method works for all versions of Excel.

· Use theFileSystemObjectobject, which uses the Microsoft Scripting Library: This method works for Excel 2000 and later.

inline Caution

Some earlier versions of Excel also supported the use of the FileSearch object. That feature was removed, beginning with Excel 2007. If you execute an old macro that uses the FileSearch object, the macro will fail.

In the sections that follow, you explore these two methods and some examples.

Using VBA file-related statements

The VBA statements that you can use to work with files are summarized in Table 11.1. Most of these statements are straightforward, and all are described in the Help system.

Table 11.1 VBA File-Related Statements

Command

What It Does

ChDir

Changes the current directory

ChDrive

Changes the current drive

Dir

Returns a filename or directory that matches a specified pattern or file attribute

FileCopy

Copies a file

FileDateTime

Returns the date and time when a file was last modified

FileLen

Returns the size of a file, in bytes

GetAttr

Returns a value that represents an attribute of a file

Kill

Deletes a file

MkDir

Creates a new directory

Name

Renames a file or directory

RmDir

Removes an empty directory

SetAttr

Changes an attribute for a file

The remainder of this section consists of examples that demonstrate some of the file manipulation commands.

A VBA function to determine whether a file exists

The following function returns True if a particular file exists and False if it doesn’t exist. If the Dir function returns an empty string, the file couldn’t be found, so the function returns False.

Function FileExists(fname) As Boolean

FileExists = Dir(fname) <>»»

End Function

The argument for the FileExists function consists of a full path and filename. The function can be used in a worksheet or called from a VBA procedure. Here’s an example:

MyFile =»c:budgeting2013 budget notes.docx»

Msgbox FileExists(MyFile)

A VBA function to determine whether a path exists

The following function returns True if a specified path exists and False otherwise:

Function PathExists(pname) As Boolean

‘ Returns TRUE if the path exists

On Error Resume Next

PathExists = (GetAttr(pname) And vbDirectory) = vbDirectory

End Function

The pname argument is a string that contains a directory (without a filename). The trailing backslash in the pathname is optional. Here’s an example of calling the function:

MyFolder =»c:usersjohndesktopdownloads»

MsgBox PathExists(MyFolder)

inline On the Web

The FileExists and PathExists functions are available on the book’s website in the file functions.xlsm file.

A VBA procedure to display a list of files in a directory

The following procedure displays (in the active worksheet) a list of files in a particular directory, along with the file size and date:

Sub ListFiles()

Dim Directory As String

Dim r As Long

Dim f As String

Dim FileSize As Double

Directory =»f:excelfilesbudgeting»

r = 1

‘ Insert headers

Cells(r, 1) =»FileName»

Cells(r, 2) =»Size»

Cells(r, 3) =»Date/Time»

Range(«A1:C1»).Font.Bold = True

‘ Get first file

f = Dir(Directory, vbReadOnly + vbHidden + vbSystem)

Do While f <>»»

r = r + 1

Cells(r, 1) = f

‘Adjust for filesize > 2 gigabytes

FileSize = FileLen(Directory & f)

If FileSize < 0 Then FileSize = FileSize + 4294967296#

Cells(r, 2) = FileSize

Cells(r, 3) = FileDateTime(Directory & f)

‘ Get next file

f = Dir()

Loop

End Sub

inline Note

The VBA FileLen function uses the Long data type. Consequently, it will return an incorrect size (a negative number) for files larger than about 2GB. The code checks for a negative value from the FileLen function and makes an adjustment if necessary.

Note that the procedure uses the Dir function twice. The first time (used with an argument), it retrieves the first matching filename found. Subsequent calls (without an argument) retrieve additional matching filenames. When no more files are found, the Dir function returns an empty string.

inline On the Web

The book’s website contains a version of this procedure that allows you to select a directory from a dialog box. The filename is create file list.xlsm.

The Dir function also accepts wildcard file specifications in its first argument. To get a list of Excel files, for example, you could use a statement such as this:

f = Dir(Directory &»*.xl??», vbReadOnly + vbHidden + vbSystem)

This statement retrieves the name of the first *.xl?? file in the specified directory. The wildcard specification returns a four-character extension that begins with XL. For example, the extension could be .xlsx, .xltx, or .xlam. The second argument for the Dir function lets you specify the attributes of the files (in terms of built-in constants). In this example, the Dir function retrieves filenames that have no attributes, read-only files, hidden files, and system files.

To also retrieve Excel files in an earlier format (for example, .xls and .xla files), use the following wildcard specification:

*.xl*

Table 11.2 lists the built-in constants for the Dir function.

Table 11.2 File Attribute Constants for the Dir Function

Constant

Value

Description

vbNormal

0

Files with no attributes. This is the default setting and is always in effect.

vbReadOnly

1

Read-only files.

vbHidden

2

Hidden files.

vbSystem

4

System files.

vbVolume

8

Volume label. If any other attribute is specified, this attribute is ignored.

vbDirectory

16

Directories. This attribute doesn’t work. Calling the Dir function with the vbDirectory attribute doesn’t continually return subdirectories.

inline Caution

If you use the Dir function to loop through files and call another procedure to process the files, make sure that the other procedure doesn’t use the Dir function. Only one»set» of Dir calls can be active at any time.

A recursive VBA procedure to display a list of files in nested directories

The example in this section creates a list of files in a specified directory, including its subdirectories. This procedure is unusual because it calls itself — a concept known as recursion.

Public Sub RecursiveDir(ByVal CurrDir As String, Optional ByVal Level As Long)

Dim Dirs() As String

Dim NumDirs As Long

Dim FileName As String

Dim PathAndName As String

Dim i As Long

Dim Filesize As Double

‘ Make sure path ends in backslash

If Right(CurrDir, 1) <>»» Then CurrDir = CurrDir &»»

‘ Put column headings on active sheet

Cells(1, 1) =»Path»

Cells(1, 2) =»Filename»

Cells(1, 3) =»Size»

Cells(1, 4) =»Date/Time»

Range(«A1:D1»).Font.Bold = True

‘ Get files

FileName = Dir(CurrDir &»*.*», vbDirectory)

Do While Len(FileName) <> 0

If Left(FileName, 1) <>».» Then ‘Current dir

PathAndName = CurrDir & FileName

If (GetAttr(PathAndName) And vbDirectory) = vbDirectory Then

‘store found directories

ReDim Preserve Dirs(0 To NumDirs) As String

Dirs(NumDirs) = PathAndName

NumDirs = NumDirs + 1

Else

‘Write the path and file to the sheet

Cells(WorksheetFunction.CountA(Range(«A:A»)) + 1, 1) = _

CurrDir

Cells(WorksheetFunction.CountA(Range(«B:B»)) + 1, 2) = _

FileName

‘adjust for filesize > 2 gigabytes

Filesize = FileLen(PathAndName)

If Filesize < 0 Then Filesize = Filesize + 4294967296#

Cells(WorksheetFunction.CountA(Range(«C:C»)) + 1, 3) = Filesize

Cells(WorksheetFunction.CountA(Range(«D:D»)) + 1, 4) = _

FileDateTime(PathAndName)

End If

End If

FileName = Dir()

Loop

‘ Process the found directories, recursively

For i = 0 To NumDirs — 1

RecursiveDir Dirs(i), Level + 2

Next i

End Sub

The procedure takes one argument, CurrDir, which is the directory being examined. Information for each file is displayed in the active worksheet. As the procedure loops through the files, it stores the subdirectory names in an array named Dirs. When no more files are found, the procedure calls itself using an entry in the Dirs array for its argument. When all directories in the Dirs array have been processed, the procedure ends.

Because the RecursiveDir procedure uses an argument, it must be executed from another procedure by using a statement like this:

Call RecursiveDir(«c:directory»)

inline On the Web

The book’s website contains a version of this procedure that allows you to select a directory from a dialog box. The filename is recursive file list.xlsm.

Using the FileSystemObject object

The FileSystemObject object is a member of Windows Scripting Host and provides access to a computer’s file system. This object is often used in script-oriented web pages (for example, VBScript and JavaScript) and can be used with Excel 2000 and later versions.

inline Caution

Windows Scripting Host can potentially be used to spread computer viruses and other malware, so it may be disabled on some systems. In addition, some antivirus software products have been known to interfere with Windows Scripting Host. Therefore, use caution if you’re designing an application that will be used on many different systems.

The name FileSystemObject is a bit misleading because it includes a number of objects, each designed for a specific purpose:

· Drive: A drive or a collection of drives

· File: A file or a collection of files

· Folder: A folder or a collection of folders

· TextStream: A stream of text that is read from, written to, or appended to a text file

The first step in using the FileSystemObject object is to create an instance of the object. You can perform this task in two ways: early binding or late binding.

The late binding method uses two statements, like this:

Dim FileSys As Object

Set FileSys = CreateObject(«Scripting.FileSystemObject»)

Note that the FileSys object variable is declared as a generic Object rather than as an actual object type. The object type is resolved at runtime.

The early binding method of creating the object requires that you set up a reference to Windows Script Host Object Model. You do this by using Tools ➜ References in VBE. After you’ve established the reference, create the object by using statements like these:

Dim FileSys As FileSystemObject

Set FileSys = CreateObject(«Scripting.FileSystemObject»)

Using the early binding method enables you to take advantage of the VBE Auto List Members feature to help you identify properties and methods as you type. In addition, you can use Object Browser (by pressing F2) to learn more about the object model.

The examples that follow demonstrate various tasks using the FileSystemObject object.

Using FileSystemObject to determine whether a file exists

The Function procedure that follows accepts one argument (the path and filename) and returns True if the file exists:

Function FileExists3(fname) As Boolean

Dim FileSys As Object ‘FileSystemObject

Set FileSys = CreateObject(«Scripting.FileSystemObject»)

FileExists3 = FileSys.FileExists(fname)

End Function

The function creates a new FileSystemObject object named FileSys and then accesses the FileExists property for that object.

Using FileSystemObject to determine whether a path exists

The Function procedure that follows accepts one argument (the path) and returns True if the path exists:

Function PathExists2(path) As Boolean

Dim FileSys As Object ‘FileSystemObject

Set FileSys = CreateObject(«Scripting.FileSystemObject»)

PathExists2 = FileSys.FolderExists(path)

End Function

Using FileSystemObject to list information about all available disk drives

The example in this section uses FileSystemObject to retrieve and display information about all disk drives. The procedure loops through the Drives collection and writes various property values to a worksheet.

inline On the Web

This workbook, named show drive info.xlsm, is available on the book’s website.

Sub ShowDriveInfo()

Dim FileSys As FileSystemObject

Dim Drv As Drive

Dim Row As Long

Set FileSys = CreateObject(«Scripting.FileSystemObject»)

Cells.ClearContents

Row = 1

‘ Column headers

Range(«A1:F1») = Array(«Drive»,»Ready»,»Type»,»Vol. Name», _

«Size»,»Available»)

On Error Resume Next

‘ Loop through the drives

For Each Drv In FileSys.Drives

Row = Row + 1

Cells(Row, 1) = Drv.DriveLetter

Cells(Row, 2) = Drv.IsReady

Select Case Drv.DriveType

Case 0: Cells(Row, 3) =»Unknown»

Case 1: Cells(Row, 3) =»Removable»

Case 2: Cells(Row, 3) =»Fixed»

Case 3: Cells(Row, 3) =»Network»

Case 4: Cells(Row, 3) =»CD-ROM»

Case 5: Cells(Row, 3) =»RAM Disk»

End Select

Cells(Row, 4) = Drv.VolumeName

Cells(Row, 5) = Drv.TotalSize

Cells(Row, 6) = Drv.AvailableSpace

Next Drv

‘Make a table

ActiveSheet.ListObjects.Add xlSrcRange, _

Range(«A1»).CurrentRegion, , xlYes

End Sub

inline Cross-Ref

Chapter 7 describes another method of getting drive information by using Windows API functions.

Zipping and Unzipping Files

Perhaps the most commonly used type of file compression is the Zip format. Even Excel 2007 (and later) files are stored in the Zip format (although they don’t use the .zip extension). A Zip file can contain any number of files, and even complete directory structures. The content of the files determines the degree of compression. For example, JPG image files and MP3 audio files are already compressed, so zipping these file types has little effect on the file size. Text files, on the other hand, usually shrink quite a bit when compressed.

inline On the Web

The examples in this section are available on the book’s website in files named zip files.xlsm and unzip a file.xlsm.

Zipping files

The example in this section demonstrates how to create a Zip file from a group of user-selected files. The ZipFiles procedure displays a dialog box so that the user can select the files. It then creates a Zip file named compressed.zip in Excel’s default directory.

Sub ZipFiles()

Dim ShellApp As Object

Dim FileNameZip As Variant

Dim FileNames As Variant

Dim i As Long, FileCount As Long

‘ Get the file names

FileNames = Application.GetOpenFilename _

(FileFilter:=»All Files (*.*),*.*», _

FilterIndex:=1, _

Title:=»Select the files to ZIP», _

MultiSelect:=True)

‘ Exit if dialog box canceled

If Not IsArray(FileNames) Then Exit Sub

FileCount = UBound(FileNames)

FileNameZip = Application.DefaultFilePath &»compressed.zip»

‘Create empty Zip File with zip header

Open FileNameZip For Output As #1

Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)

Close #1

Set ShellApp = CreateObject(«Shell.Application»)

‘Copy the files to the compressed folder

For i = LBound(FileNames) To UBound(FileNames)

ShellApp.Namespace(FileNameZip).CopyHere FileNames(i)

‘Keep script waiting until Compressing is done

On Error Resume Next

Do Until ShellApp.Namespace(FileNameZip).items.Count = i

Application.Wait (Now + TimeValue(«0:00:01»))

Loop

Next i

If MsgBox(FileCount &» files were zipped to:» & _

vbNewLine & FileNameZip & vbNewLine & vbNewLine & _

«View the zip file?», vbQuestion + vbYesNo) = vbYes Then _

Shell»Explorer.exe /e,» & FileNameZip, vbNormalFocus

End Sub

The ZipFiles procedure creates a file named compressed.zip and writes a string of characters, which identify it as a Zip file. Next, a Shell.Application object is created, and the code uses its CopyHere method to copy the files to the Zip archive. The next section of the code is a Do Until loop, which checks the number of files in the Zip archive every second. This step is necessary because copying the files could take some time, and if the procedure ends before the files are copied, the Zip file will be incomplete (and probably corrupt).

When the number of files in the Zip archive matches the number that should be there, the loop ends and the user is presented with a message box asking if he wants to see the files. Clicking the Yes button opens a Windows Explorer window that shows the zipped files.

inline Caution

The ZipFiles procedure presented here was kept simple to make it easy to understand. The code does no error checking and is not flexible. For example, there is no option to choose the Zip filename or location, and the current compressed.zip file is always overwritten without warning. It’s certainly no replacement for the zipping tools built into Windows, but it’s an interesting demonstration of what you can do with VBA.

Unzipping a file

The example in this section performs the opposite function of the preceding example. It asks the user for a ZIP filename and then unzips the files and puts them in a directory named Unzipped, located in Excel’s default file directory.

Sub UnzipAFile()

Dim ShellApp As Object

Dim TargetFile

Dim ZipFolder

‘ Target file & temp dir

TargetFile = Application.GetOpenFilename _

(FileFilter:=»Zip Files (*.zip), *.zip»)

If TargetFile = False Then Exit Sub

ZipFolder = Application.DefaultFilePath &»Unzipped»

‘ Create a temp folder

On Error Resume Next

RmDir ZipFolder

MkDir ZipFolder

On Error GoTo 0

‘ Copy the zipped files to the newly created folder

Set ShellApp = CreateObject(«Shell.Application»)

ShellApp.Namespace(ZipFolder).CopyHere _

ShellApp.Namespace(TargetFile).items

If MsgBox(«The files was unzipped to:» & _

vbNewLine & ZipFolder & vbNewLine & vbNewLine & _

«View the folder?», vbQuestion + vbYesNo) = vbYes Then _

Shell»Explorer.exe /e,» & ZipFolder, vbNormalFocus

End Sub

The UnzipAFile procedure uses the GetOpenFilename method to get the Zip file. It then creates the new folder and uses the Shell.Application object to copy the contents of the Zip file to the new folder. Finally, the user can choose to display the new directory.



How to use external data connections in Excel? Today’s tutorial is all about data import (SQL, CSV, and XML) and the managing of data sources. Stay with us!

It is not surprising that we rarely store databases and a large amount of raw data in Excel worksheets. The main reason for this is that Excel was not made for this.

Use external data connections to build a dashboard, and you have to work with a considerable amount of data. We think that the subject is so important. So, we provide a whole separate article about it.

The most common External Data Connections

The most important data sources are:

  • SQL database
  • CSV file
  • XML

How can we import data using various external data connections into Excel?

The starting point is always the same. First, go to the Data tab on the ribbon. Then, choose ‘Get data’ or ‘From Text/CSV.’ Then, of course, we can import data with the help of a web query also.

data connections external data sources

Connect to External Data Sources

We’ll use the ‘AdventureWorks’ SQL Server database. It’s well known and used by many. SQL Server Management studio will help us import the given database from a backup.

excel-adventureworks-database

First, start Excel.
Choose the Get Data > From database > From SQL Server Database menu.

initialize SQL connection-db

In the next window, we have to give the name of the SQL Server.

The name of the Server is a mandatory field. The name of the database is optional.

excel-data-connections-SQL-db-login

The Navigator will appear by clicking on the OK button, and we can find multiple things here. In our example, we’ll use the AdventureWorks database table.

We want to direct your attention to the ‘Select multiple items’ checkbox. If we do not check it, we can only import one table.
And what happens if we check it? Then we were able to import the highlighted table AND all the relevant connected tables also!

excel-navigator-pane-1

Now we’d like to import the ‘Person.Address’ table.

It can be seen in the figure below. If we need the connected tables also, we have to check the ‘Select related tables’ button, located at the bottom of the window.

select related tables data import SQL

We have highlighted the data.

Now we’ll import with the help of the external data source. Then, finally, we’ll transfer the data into Excel by clicking on the Load button.
If we pay more attention to the button, we can see a drop-down list.

Let’s try out how the ‘Load to’ option work!

choose the load to option

Take a closer look at the Import Data window!

We can see we have more options for data import. This chapter will show you how to create a data structure.

The Import Data Window: Select views

externa-data-sources-excel-import-window

We can choose a view and layout for our project using the import data window.

  • Table: we can display data in tabular form
  • Pivot Table Report: we don’t have to specifically explain the advantages of Pivot tables. Choose this if you’d like to group the data in a short time. If you’d like to apply the drill-down method, this is the best choice!
  • Pivot Chart: using the columns of the Pivot table, we can make a chart
  • Only create a connection: if we don’t need the data right away, then we only create the connection between the SQL database and the Excel worksheet.
  • Add this data to Data Model: in this case, the highlighted data will upload into the Power Pivot Data Model.

Explanation of the Get and Transform function: If you use this function in Excel, you create a query in your workbook. This query enables you to manage data using various external data sources. For example, suppose you want to refresh your data and keep your dashboard always-on use, the built-in Data Model in Excel. Of course, the most effective is to use the tabular format. So let’s choose this option!

How to manage and refresh External Data Connections?

We are already done with an important step.

Now we have our data in Excel. What happens when data changes in the source database? How can we keep data up to date? We’ll find the answer in this chapter.

externa-data-sources-excel-after-import

Check the ‘Queries and Connections’ window! It’s located on the right-hand side.

You can see the imported records and all related records of the Person.Address table. Every single database table is on a separate Worksheet.

Refreshing Data Connections manually

Usually, we use two methods to refresh existing data connections. First, we can find this menu on the ribbon in the Table Tools tab. Then, click on Refresh / Refresh all icons to refresh the data connections manually.

It is important to note a big difference between the two. We use Refresh when we only want to refresh the data of the given Worksheet. For example, a specific database table. When we use the Refresh all button, every table structure and all the Worksheets are being refreshed.

excel-manually-refresh

Using auto-refresh control to Scheduled Data Import

We also have the option to automate this process.

How to schedule refreshing? Set a 10-minute interval and forget about the manual work.

Click on the ‘Existing connections’ icon on the Data tab.

manage existing data connections

We’ll see the following window appear. We see the relevant connections of the workbook in one list.

After a right-click, you can choose the ‘Edit Connection Properties’ button.

edit connection properties

The Query Properties Window

You can find all the adjustments on the ‘Usage’ tab. First, let us set the parameters of the query! Here are the details below:

The Refresh Control section informs us of the actual setups.

  • Enable Background refresh: This is a query running in the background. We’ll be informed about the status of the process. Check the marked section on the picture. The extraction is in progress.
enable background refresh
  • Refresh every x minutes: We can set the intervals of the import. Our data set will be updated using external data sources.
  • Refresh Data when opening file: This setting is automatically refreshing the data connection the moment Excel Workbook is opened. Usually, we shouldn’t use this option. If a large query starts up, it can even freeze up Excel. We’re better off if we refresh data after we’ve opened the workbook.
  • Refresh This Connection on Refresh All: We already talked about this, but it is very important to let’s see it again! If we allow this option, all imported tables will refresh. (If not, then only the data on the active Worksheet will refresh.)
externa-data-sources-excel-schedule-13

We can find more information about the data connection on the Definition tab. Add a specific name for the query. In the description field, we can give notes also.

Now let us see further options:

  • Connection Type: The type of the connection, in our case, is OLE DB Query.
  • Connection file: We can save the connection file to any place we want to. Also, we can browse an already created connection file.
  • Connection String: It describes how and what we’ll import using external data sources.
  • Command type: In our example, this is SQL.
  • Command text: If you want, you can write your own SQL query. In this case, we import all records from the Person.Address table.
excel-data-connection definition

Importing CSV files to Excel – External Data Connection Example

In this chapter, we’ll import a CSV file containing sales records into Excel. This will be a lot easier than the SQL data import.

Choose the ‘From text / CSV’ option from the ‘Get and Transform Data’ option on the Data tab.

import externa-data-excel-csv-ribbon

Locate the file and click import.

externa-data-connections-excel-csv-import

Before the data import, a preview window will appear. You can set the code page in the ‘File Origin’ section.

In the ‘Delimiter’ menu, you can give the character that will separate the columns of the imported table. The default ‘comma’ setting is the right one for us.

There’s the usual ‘Load / Load To’ button on the bottom right-hand corner. We have talked about this before. The Tabular format is perfect for us now.

Click on the Load button.

external data connect sales data

The file containing 100 sales records is in Excel in a matter of moments using external data sources!

externa-data-sources-excel-csv-ready

Import Data from Website into Excel using XML files

We have two choices to import from XML to Excel. We either use a specific URL address or browse the file itself.

Using Web query

In this example, we’ll import a short restaurant menu into Excel using a web query.

excel-web-query

Type the URL and click OK.

data-sources-excel-url

On the left-hand side of the Navigator Window, highlight the table we would like to import. After the highlight on the right-hand side, we’ll see a preview.

food table

Click on the Load button.

With the help of the external data source, the table’s data will be on the given Worksheet.

external data has been loaded

Import a local XML file

On the Data Tab, choose Get Data > From file > From XML menu.

manual xml file import into excel

Click on the Import button and open the XML file.

xml data import part 2

From here on, the steps are entirely the same as described in the web query tutorial.

Conclusion

In today’s article, we endeavored to show you the most critical external data sources. We can choose multiple formats for the data needed to be imported. Last but not least, we talked about the management of data connections. Excel is excellently capable of making charts, reports, and various data visualizations. We should leave the managing of large data to external data sources.

Download the examples!

Data is the bloodstream of any business entity. Businesses use different programs and formats to save the data depending on the business data storage requirements. You could have a payroll program powered by a database engine, you could have data in a CSV file or even from a website that you would like to analyse in Excel. This article shows you how you can achieve the above.

What is external data source?

External data is data that you link/import into excel from a source that resides outside excel.

Examples of external include the following

  • Data stored in a Microsoft Access database. This could the information from a custom application i.e. Payroll, Point of Sale, Inventory, etc.
  • Data from SQL Server or other database engines i.e. MySQL, Oracle, etc. – This could be information from a custom application
  • From a web site/web service – this could be information from a Web services i.e. currency exchange rates from the internet, stock prices, etc.
  • Text file i.e. CSV, tab separated, etc. – this could be information from a third party application that does not provide direct links. Such data could include bank payments exported to comma separated file CSV, etc.
  • Other types i.e. HTML data, Windows Azure Market Place, etc.

Website(XML data) external data source example

In this example to import XML into Excel, we will assume we are trading the Euro currency and would like to get the exchange rates from the European Central Bank web service. The currency exchange rate API link is http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

  • Open a new workbook
  • Click on the DATA tab on the ribbon bar
  • Click on “From Web” button
  • You will get the following window

How to Import XML Data into Excel

  1. Enter http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml in the address
  2. Click on Go button, you will get the XML data preview
  3. Click on Import button when done

You will get the following options dialogue window

Connecting Microsoft Excel to External Data Sources

  • Click on OK button
  • You will get the following Excel import XML data

Steps to Import XML Data into Excel

Let’s take another example on how to import XML file in Excel, this time you have local XML not in form of web link. You can download XML File below.

Download the XML File

Here is a step by step process on how to open XML file in Excel:

Step 1) Create a new workbook in Excel

  • Open a new workbook
  • Click on the DATA tab on the ribbon bar
  • Click on “From Other Source”

How to Import XML to Excel

Step 2) Select the XML as Data source

  • Then click on “From XML Data Import”

Steps for connecting Microsoft Excel to External Data Sources

Step 3) Locate and select the XML file

  • Now select the XML File to Excel sheet

You will get the options dialogue window as above example

  • Click on OK button
  • You will get the following data

How to Connect Microsoft Excel to External Data Sources

Summary

Excel has powerful features that allow us to analyse numeric data and create visual reports such as charts. You can take advantage of external data importation to create your own custom reports that meet your business reporting requirements.

You all must have heard of Excel Workbook Connections but do know how to manage workbook connection in Excel? Well if you are not having any idea of enabling data connection in Excel workbook.

In that case our, this Excel workbook connections tutorial will help in grabbing every pinch of information reading this. So, that any Excel user can easily perform and manage external data connections in Excel.

What Is Data Connection In Excel?

What Is Data Connection In Excel?

Data of any Excel workbook can only be bring from different locations. Firstly, either the data is directly stored in your Excel workbook. Or secondly it may be saved in the external data source, like a database, an OLAP (Online Analytical Processing cube) or text file.

Using the data connection in Excel, external data sources are well connected with Excel workbook. Basically this data connection in Excel contains set of information about how to log in, query, locate, and perfectly access the external data source.

After connecting your excel workbook with external data source. One can easily use the refresh option to extract the updated data from their workbook. Using this way, user can get the most updated version of their data including the changes made in the data since it was last refreshed.

Well the Connection information can be stored in a connection file or in the workbook like Universal Data Connection (UDC) file (.udcx) or Office Data Connection (ODC) file (.odc)

These connection files are very useful to share connections on regular basis also to facilitate data source administration.

If you are using the connection file for connecting with the data source. Then in that case Excel will copies down the connection details from the connection file into your Excel workbook.

Different Ways To Perform Excel Workbook Connections

Different Ways To Perform Excel Workbook Connections

In this Excel workbook connections tutorial we will learn 3 different ways to use Data Connection In Excel 2010/2013/2016/2019:

  • Workbook Connections dialog box
  • Creating an Office Data Connection (ODC) file (.odc)
  • Refresh external data connection

Method 1: Excel Workbook Connections Using Workbook Connections Dialog Box

Excel Workbook Connections Using Workbook Connections Dialog Box

Excel Workbook Connections dialog box option helps in easy managing of single or multiple connections with the external data sources of your workbook. Apart from this the Workbook Connections dialog box is helpful to perform the following tasks:

  • It helps to edit, refresh, create and delete connections which are used in Excel workbook.
  • Show the location of each connection that is already been used in the current Excel workbook.
  • Easy diagnosis of error message regarding external data connections.
  • With this option, user can either redirect connection to different data or to the different server. Or alternatively user can easily replace the connection file with the existing connection.
  • It becomes too easy to make & share connection files.

Steps To Manage Excel Workbook Connection Using Workbook Connections Dialog Box

Here is how to manage connections in your current using Excel workbook i.e by using Workbook Connections dialog box:

Identify a connection

In the top portion of the dialog box, all connections in the workbook are displayed automatically with the following information:

Column Comment
Name  connection name is, defined within Connection Properties dialog box.
Description A short description about connection, is mentioned in Connection Properties dialog box.
Last refreshed when was the connection was last refreshed such as it’s date and time appears in this section. If it is blank, then it means that the connection has not refreshed yet.

Add a connection

  • Tap to the Add option to get the dialog box of Existing Connections.

Display Connection Information

  • For this you need to choose a connection from the opened Existing Connections dialog box.
  • Now hit the Properties option and this will open the dialog box of Connection Properties.

Refresh The External Data.

  • Hit the arrow option present next to the Refresh option. After then perform anyone of the following:
    • If you want to refresh any specific connections only, then make selections of those connections. After then tap to the Refresh option.
    • For refreshing all connections of your workbook, just clear off all the connections. After that tap to the Refresh All option.
    • If you want to get the status information about refresh operation then choose the connections about which you want to extract information. After then hit on the Refresh Status option.
    • For stopping down the current running refresh operation just tap to the Cancel Refresh option.

Remove One Or More Connections

  • Choose the connections which you wants to remove from your Excel workbook. After then tap to the Remove option.

Notes:

  • Well this option appears disabled to you if your workbook is protected one or if it is an object, like PivotTable report, which uses the protected connection.
  • Removing connection will only deletes off the connection. It will not remove any data or any object from your Excel workbook.

Important: By removing connection you are actually breaking the connection with the data source which may leads to cause unintentional consequences, Like different formula results or you may face difficulty in accessing Excel features.

Method 2: Excel Workbook Connections Using Refresh External Data Connection Option

Excel Workbook Connections Using Refresh External Data Connection Option

User can connect their Excel workbook with an external data source, like to another Excel workbook, SQL Server database or an OLAP cube.

Well this connection information gets displayed on your workbook as PivotTable report, PivotChart, table.

For keeping the data of your Excel workbook updated you can make use of “Refresh” option to link the data with its source.

So whenever you will refresh your connection, you will only get the most current updated data.

Step To Use Refresh External Data Connection Option

For connections just tap to any cell of your Excel table which uses the connection. After then perform any of the following operation:

  • Automatically refresh data when excel workbook is opened
  • Automatically refresh data at regular interval

Step To Automatically Refresh Data When Excel Workbook Is Opened

  • Tap to the cell present within the external data range.
  • Now on the Data tab, go to the Queries & Connections Hit the arrow key present within the Refresh All option, and from this tap to the Connection Properties.

refresh data when workbook opened---1

  • From the opened dialog box of Connection Properties dialog tap to the Usage tab, within Refresh control. After then choose the check box “Refresh data when opening the file”.
  • In order to save your workbook with the complete query definition excluding external data. You need to choose the check box “Remove data from the external data range before saving the workbook”.

Step To Automatically refresh data at regular interval:

  • Tap to the cell present within the external data range.
  • Now on the Data tab, go to the Queries & Connections Hit the arrow key present within the Refresh All option, and from this tap to the Connection Properties.

refresh data when workbook at regular interval---1

  • In the opened Connection Properties dialog box. Hit Usage tab option.
  • Choose the check box Refresh every. After then set the minute interval that will automatically refresh your data after certain period of time.

Method 3: Excel Workbook Connections By Creating An Office Data Connection (ODC) File

Excel Workbook Connections By Creating An Office Data Connection (ODC) File

By making use of the Data Connection Wizard or Connection Properties dialog box one can easily use their Excel worksheet to create an Office Data Connection (ODC) file (.odc).

  1. You can perform any of the following task:
    • Make new connection with data source. To catch more information, have a look at following topics :
      • Connect to SQL Server Analysis Services Database (Import)
      • Import or export text files
      • Move data from Excel to Access
  • Or you can just make use of the existing connection. For more information, see Connect to (Import) external data.
  1. After then save the connection detail into the connection file. For this, just make a tap to the Export Connection File option present on the Definition tab of Connection Properties dialog box. This will open the File Save dialog box, so save your current connection information into the ODC file.

Wrap Up:

Hopefully, all the above mentioned fixes to setup Excel Workbook Connections will help you in easy using of data connection in your respective Excel 2010/2013/2016/2019 application. Apart from this if you you have any other query to ask then, ask it in our comment section.

Priyanka is an entrepreneur & content marketing expert. She writes tech blogs and has expertise in MS Office, Excel, and other tech subjects. Her distinctive art of presenting tech information in the easy-to-understand language is very impressive. When not writing, she loves unplanned travels.

Понравилась статья? Поделить с друзьями:
  • What is excel workbook path
  • What is excel wikipedia
  • What is excel vba userform
  • What is excel vba training
  • What is excel vba array