Содержание
- О подключении к данным в Visio
- О наборах записей данных и подключениях к данным
- Добавление объектов DataRecordset
- Программный доступ к данным в наборе записей данных
- Поддержка и обратная связь
- Name already in use
- VBA-Docs / visio / Concepts / about-connecting-to-data-in-visio.md
О подключении к данным в Visio
Функции подключения к данным доступны только для лицензированных пользователей Microsoft Visio профессиональный 2013.
Существует четыре аспекта подключения к данным в Visio:
Подключение к источнику данных
Связывание фигур с данными
Графическое представление связанных данных
Обновление связанных данных, измененных в источнике данных, обновление связанных фигур и разрешение последующих возможных конфликтов
Как правило реализация этих аспектов выполняется в перечисленном порядке. Это означает, что сначала вы подключаете документ Visio к источнику данных, затем связываете фигуры документа с данными в источнике, графически представляете данные в связанных фигурах и обновляете связанные данные при необходимости. С каждым из этих аспектов связаны новые объекты и элементы в объектной модели Visio. В этой статье рассматривается первый из этих аспектов: подключение документа Visio к источнику данных. Дополнительные сведения о других аспектах подключения к данным см. в следующих статьях:
Чтобы программно подключить документ Visio к источнику данных, можно использовать API Visio для подключений к данным, включающий следующие объекты и соответствующие элементы:
Коллекция DataRecordsets
Объект DataRecordset
Объект DataConnection
Коллекция DataColumns
Объект DataColumn
О наборах записей данных и подключениях к данным
В каждом объекте Document приложения Visio есть коллекция DataRecordsets. Она является пустой до подключения к источнику данных. Чтобы подключить документ Visio к источнику данных, нужно добавить объект DataRecordset в коллекцию DataRecordsets документа. В свою очередь объект DataRecordset содержит коллекцию DataColumns объектов DataColumn, каждый из которых сопоставлен с соответствующим столбцом (полем) в источнике данных.
Источники данных, к которым можно подключиться, включают электронные таблицы Excel, базы данных Access и SQL Server, списки SharePoint, а также другие источники данных OLEDB или ODBC, например база данных Oracle. Когда вы добавляете объект DataRecordset путем подключения к одному из этих источников данных, Visio выделяет подключение в объекте DataConnection, и считается, что объект DataRecordset подключен.
Вы также можете добавить объект DataRecordset с помощью XML-файла, соответствующего классической XML-схеме набора записей данных ADO Classic (ADO версии 2.x), в качестве источника данных. Полученный объект DataRecordset считается не подключенным. Соединение между источником данных и объектом DataRecordset выполняется только в одну сторону: из источника данных в документ Visio. Если данные в источнике изменяются, вы можете обновить данные в документе, чтобы отразить эти изменения. Однако вы не можете изменить данные в документе и передать их в источник данных.
Добавление объектов DataRecordset
Чтобы добавить объект DataRecordset в коллекцию DataRecordsets, можно использовать один из следующих трех методов в зависимости от источника данных, к которому нужно подключиться, и необходимости передачи методу строки подключения и строки команды запроса или сохраненного файла подключения к данным Office (ODC), содержащего сведения о подключении и запросе.
В следующем примере макроса Visual Basic для приложений (VBA) показано, как можно использовать метод Add для подключения документа Visio к данным на листе Excel, в этом случае в примере книги ORGDATA.XLS, входящей в комплект Visio:
Если запустить этот код в неанглоязычных сборках Visio, путь к файлу ORGDATA.XLS, представленный в виде «Samples1033ORGDATA.XLS», будет другим. Подставьте правильный путь для своей версии Visio в коде.
Метод Add возвращает объект DataRecordset и использует четыре параметра:
ConnectionIDOrString. Идентификатор существующего объекта DataConnection или строки подключения для указания нового подключения к источнику данных. Если передается идентификатор существующего объекта DataConnection, используемого в одном или нескольких других наборах записей данных, набор записей данных становится транзакционным набором записей группы. Все наборы записей данных в группе обновляются при каждой операции обновления данных. Вы можете определить соответствующую строку подключения, применив сначала мастер выбора данных в пользовательском интерфейсе Visio, чтобы создать такое же подключение, записав макрос во время работы мастера и скопировав строку подключения из кода макроса.
CommandString. Строка, указывающая таблицу базы данных или лист Excel и поля (столбцы) в таблице или листе, содержащие данные, которые нужно запросить. Командная строка также передается методу DataRecordset.Refresh при обновлении данных в наборе записей.
AddOptions. Сочетание одного или нескольких значений из перечисления VisDataRecordsetAddOptions. Эти значения определяют конкретные действия набора записей данных и позволяют, например, предотвратить появление запрошенных данных из набора записей в окне Внешние данные в пользовательском интерфейсе Visio или их обновление с помощью действий пользователя. После назначения этого значения его нельзя изменить, пока существует объект DataRecordset.
Name. Необязательная строка, присваивающая набору записей данных отображаемое имя. Если указать отображение данных из набора записей в окне Внешние данные в пользовательском интерфейсе Visio, передаваемое имя появляется на вкладке этого окна, соответствующей набору записей данных. В нашем примере отсутствует существующее подключение к данным, поэтому в качестве первого параметра метода Add передается strConnection — определенная нами строка подключения. Для второго параметра мы передаем strCommand, определяемую нами командную строку, которая позволяет Visio выбрать все столбцы на указанном листе. В качестве третьего параметра метода Add передается нуль, чтобы указать действие по умолчанию для набора записей данных, а в качестве последнего параметра передается значение Org Data — отображаемое имя, определенное для набора записей данных.
В следующем примере кода показано, как получить объект DataConnection, созданный при добавлении объекта DataRecordset в коллекцию DataRecordsets. Он печатает строку подключения, связанную с объектом DataConnection, в окне интерпретации, обращаясь к свойству ConnectionString объекта DataConnection.
Аналогично получению строки подключения, связанной с объектом DataConnection, путем обращения к свойству ConnectionString вы можете получить командную строку, связанную с объектом DataRecordset, обратившись к его свойству CommandString. Оба этих свойства можно назначать, поэтому вы можете в любой момент изменить источник данных, связанный с объектом DataRecordset, или запрос, связанный с объектом DataConnection, при этом изменения не отображаются в документе до обновления данных. Дополнительные сведения об обновлении данных см. в статье О связывании фигур с данными.
Программный доступ к данным в наборе записей данных
Когда вы импортируете данные, приложение Visio назначает целочисленные идентификаторы строк, начиная с 1, для каждой строки данных в итоговом наборе данных с учетом порядка строк в исходном источнике данных. В Visio идентификаторы строк данных используются для отслеживания строк, если они связаны с фигурами и если обновляются данные. Если нужно получить доступ к строкам данных программным способом, используйте эти идентификаторы строк данных. Сведения о том, как операции обновления данных влияют на порядок строк, см. в статье О связывании фигур с данными.
Используйте метод DataRecordset.GetDataRowIDs для получения массива идентификаторов всех строк в наборе данных, где каждая строка представляет одну запись данных. Метод GetDataRowIDs использует в качестве параметра строку условий, соответствующую руководствам, указанным в API объекта данных ActiveX (ADO) для настройки свойства ADO.Filter. Указав соответствующие условия и используя операторы AND и OR для разделения предложений, можно отфильтровать сведения в наборе записей данных, чтобы возвратить только определенные строки набора данных. Чтобы не применять фильтр (т. е. для получения всех строк), передайте пустую строку («»). Дополнительные сведения о строках условий см. в статье Свойство Filter в справочнике по API ADO 2.x. После получения идентификаторов строк данных можно использовать метод DataRecordset.GetRowData, чтобы получить все данные, хранящиеся в каждом столбце строки данных. Дополнительные сведения о столбцах данных см. в статье О связывании фигур с данными.
В следующем примере кода показано, как использовать методы GetDataRowIDs и GetRowData, чтобы возвратить идентификатор каждой строки и получить данные, хранящиеся в каждом столбце каждой строки переданного набора записей данных. В нем используются два вложенных цикла For…Next для итерации по всем строкам в наборе записей, а затем для итерации по всем столбцам для каждой строки. Код выводит сведения, возвращаемые в окне интерпретации. Обратите внимание, что вы передаете пустую строку методу GetDataRowIDs, чтобы пропустить фильтрацию и получить все строки из набора записей. После вызова процедуры обратите внимание, что первый показанный набор данных (соответствующий первой строке данных) содержит заголовки всех столбцов данных в наборе записей данных.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Name already in use
VBA-Docs / visio / Concepts / about-connecting-to-data-in-visio.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
Copy raw contents
Copy raw contents
About connecting to data in Visio
[!NOTE] Data-connectivity features are available only to licensed users of Microsoft Visio Professional 2013.
There are four aspects of data connectivity in Visio:
Connecting to a data source
Linking shapes to data
Displaying linked data graphically
Refreshing linked data that has changed in the data source, updating linked shapes, and resolving any subsequent conflicts that may arise
Typically, you approach these aspects in the order in which they are listed; that is, you first connect your Visio drawing to a data source, then link shapes in your drawing to data in the data source, display the data in linked shapes graphically, and refresh the linked data when necessary. Each of these aspects has new objects and members associated with it in the Visio object model. This topic deals with the first of these aspects, connecting your Visio drawing to a data source. For more information about the other aspects of data connectivity, see the following topics:
To connect your Visio drawing to a data source programmatically, you can use the Visio API for data connectivity, which includes the following objects and their associated members:
DataRecordsets collection
DataRecordset object
DataConnection object
DataColumns collection
DataColumn object
About Data Recordsets and Data Connections
Each Visio Document object has a DataRecordsets collection, which is empty until you make a connection to a data source. To connect a Visio document to a data source, you add a DataRecordset object to the DataRecordsets collection of the document. A DataRecordset object in turn has a DataColumns collection of DataColumn objects, each of which is mapped to a corresponding column (field) in the data source.
Data sources you can connect to include Excel spreadsheets, Access and SQL Server databases, SharePoint lists, and other OLEDB or ODBC data sources, such as an Oracle database. When you add a DataRecordset object by connecting to one of these data sources, Visio abstracts the connection in a DataConnection object, and the DataRecordset object is said to be connected.
You can also add a DataRecordset object by using an XML file that conforms to the ADO Classic (ADO version 2.x) Data Recordset XML schema as the data source. The resulting DataRecordset object is said to be connection-less. The connection between a data source and a DataRecordset object only goes one way—from the data source to the Visio drawing. If data in the source changes, you can refresh the data in the drawing to reflect those changes. You cannot, however, make changes in the data in the drawing and then push those changes back to the data source.
Adding DataRecordset objects
To add a DataRecordset object to the DataRecordsets collection, you can use one of the following three methods, depending on the data source you want to connect to and whether you want to pass the method a connection string and query command string or a saved Office Data Connection (ODC) file that contains the connection and query information:
The following Visual Basic for Applications (VBA) sample macro shows how you might use the Add method to connect a Visio drawing to data in an Excel worksheet, in this case, in the ORGDATA.XLS sample workbook that is included with Visio:
[!NOTE] If you run this code on non-English builds of Visio, the path to the file ORGDATA.XLS, shown here as «Samples1033ORGDATA.XLS,» will be different. Substitute the correct path for your version of Visio in your code.
The Add method returns a DataRecordset object and takes four parameters:
ConnectionIDOrString The ID of an existing DataConnection object or the connection string to specify a new data-source connection. If you pass the ID of an existing DataConnection object that is currently being used by one or more other data recordsets, the data recordsets become a transacted group recordset. All data recordsets in the group are refreshed whenever a data-refresh operation occurs. You can determine an appropriate connection string by first using the Data Selector Wizard in the Visio user interface (UI) to make the same connection, recording a macro while running the wizard, and then copying the connection string from the macro code.
CommandString The string that specifies the database table or Excel worksheet and specifies the fields (columns) within the table or worksheet that contain the data you want to query. The command string is also passed to the DataRecordset.Refresh method when the data in the recordset is refreshed.
AddOptions A combination of one or more values from the VisDataRecordsetAddOptions enumeration. These values specify certain data recordset behaviors, and make it possible, for example, to prevent the queried data in the recordset from appearing in the External Data window in the Visio UI or from being refreshed by user actions. Afteryou assign this value, you cannot change it for the duration of the DataRecordset object.
Name An optional string that gives the data recordset a display name. If you specify for data from the recordset to be displayed in the External Data window in the Visio UI, the name you pass appears on the tab of that window that corresponds to the data recordset. In our example, there is no existing data connection, so for the first parameter of the Add method, we pass strConnection, the connection string we defined. For the second parameter, we pass strCommand, the command string we defined, which directs Visio to select all columns from the worksheet we specified. For the third parameter of the Add method, we pass zero to specify default behavior of the data recordset, and for the last parameter, we pass Org Data, the display name we defined for the data recordset.
The following sample code shows how to get the DataConnection object that was created when we added a DataRecordset object to the DataRecordsets collection. It prints the connection string associated with the DataConnection object in the Immediate window by accessing the ConnectionString property of the DataConnection object.
Just as you can get the connection string associated with a DataConnection object by accessing its ConnectionString property, you can get the command string associated with a DataRecordset object by accessing its CommandString property. Both of these properties are assignable, so you can change the data source associated with a DataRecordset object or the query associated with a DataConnection object at any time, although changes are not reflected in your drawing until you refresh the data. For more information about refreshing data, see About Linking Shapes to Data.
Accessing data in Data Recordsets programmatically
When you import data, Visio assigns integer row IDs, starting with the number 1, to each data row in the resulting data recordset, based upon the order of rows in the original data source. Visio uses data row IDs to track the rows when they are linked to shapes and when data is refreshed. If you want to access data rows programmatically, you must use these data row IDs. For information about how data-refresh operations affect row order, see About Linking Shapes to Data.
Use the DataRecordset.GetDataRowIDs method to get an array of the IDs of all the rows in a data recordset, where each row represents a single data record. The GetDataRowIDs method takes as its parameter a criteria string, which is a string that conforms to the guidelines specified in the ActiveX Data Object (ADO) API for setting the ADO.Filter property. By specifying appropriate criteria and using AND and OR operators to separate clauses, you can filter the information in the data recordset to return only certain data recordset rows selectively. To apply no filter (that is, to get all the rows), pass an empty string («»). For more information about criteria strings, see the Filter Property topic in the ADO 2.x API Reference. After you retrieve the data-row IDs, you can use the DataRecordset.GetRowData method to get all the data stored in each column in the data row. For more information about data columns, see About Linking Shapes to Data.
The following sample code shows how to use the GetDataRowIDs and GetRowData methods to return the row ID of each row and then get the data stored in each column in every row of the data recordset passed in. It uses two nested For…Next loops to iterate through all the rows in the recordset and then, for each row, iterate through all the columns in that row. The code displays the information returned in the Immediate window. Note that you pass an empty string to the GetDataRowIDs method to bypass filtering and get all the rows in the recordset. After you call the procedure, note that the first set of data shown (corresponding to the first data row) contains the headings for all the data columns in the data recordset.
Источник
-
#2
Try this
Code:
Option Explicit
Sub VisioFromExcel()
Dim AppVisio As Object
Dim oCharacters As Object
Dim lX As Long
Dim sChar As String
Set AppVisio = CreateObject("visio.application")
AppVisio.Visible = True
For lX = 1 To Cells(Rows.Count, 1).End(xlUp).Row
AppVisio.Documents.AddEx "block_u.vst", 0, 0
AppVisio.Windows.ItemEx(lX).Activate
AppVisio.ActiveWindow.Page.Drop AppVisio.Documents.Item("BLOCK_U.VSS").Masters.ItemU("Box"), 1.35, 9.8
AppVisio.ActiveWindow.Page.Shapes.ItemFromID(1).CellsSRC(visSectionCharacter, 0, visCharacterSize).FormulaU = "20 pt"
Set oCharacters = AppVisio.ActiveWindow.Page.Shapes.ItemFromID(1).Characters
oCharacters.Begin = 0
oCharacters.End = Len(oCharacters)
sChar = Cells(lX, 1).Value
oCharacters.Text = sChar
Next
Set oCharacters = Nothing
Set AppVisio = Nothing
End Sub
-
#3
Hi Phil,
Thanks very much for your reply — it is working perfectly!!!
Rob
-
#4
Great. Thanks for the feedback.
-
#5
This macro works fine but produces a new Visio drawing for each Excel cell in the range.
How would I modify the macro to Drop the shapes on the SAME Visio page? I don’t care about positioning or if they cover up each other.
I want to copy ALL the shapes at one time, rather than having to open each Visio drawing and copy.
Thanks, Joe
-
#6
All shapes on same page
Code:
Option Explicit
Sub VisioFromExcel()
Dim AppVisio As Object
Dim vsoCharacters1 As Visio.Characters
Dim lX As Long
Dim dXPos As Double
Dim dYPos As Double
'Const visSectionCharacter = 3
'Const visCharacterSize = 7
Set AppVisio = CreateObject("visio.application")
AppVisio.Visible = True
AppVisio.Documents.AddEx "", visMSDefault, 0 'Open Blank Visio Document
AppVisio.Documents.OpenEx "basic_u.vss", visOpenRO + visOpenDocked 'Add Basic Stencil
dXPos = AppVisio.ActivePage.PageSheet.Cells("PageWidth") / 2
dYPos = AppVisio.ActivePage.PageSheet.Cells("PageHeight") / 2
For lX = 1 To Cells(Rows.Count, 1).End(xlUp).Row
AppVisio.Windows.ItemEx(1).Activate
AppVisio.ActiveWindow.Page.Drop AppVisio.Documents.Item("BASIC_U.VSS").Masters.ItemU("Square"), dXPos, dYPos
Set vsoCharacters1 = AppVisio.ActiveWindow.Page.Shapes.ItemFromID(lX).Characters
vsoCharacters1.Begin = 0
vsoCharacters1.End = 0
vsoCharacters1.Text = CStr(Cells(lX, 1).Value)
AppVisio.ActiveWindow.Page.Shapes.ItemFromID(lX).CellsSRC(visSectionCharacter, 0, visCharacterSize).FormulaU = "36 pt"
Next
Set AppVisio = Nothing
End Sub
-
#7
I tried that macro and got compile error «User-defined type not defined» on Dim vsoCharacters1 As Visio.Characters. I changed that to Dim vsoCharacters1 As Object.
Then got compile errors on visOpenRO not defined. My target is Visio 2007 Standard.
Thanks,
Joe
-
#8
Open the VBA Editor and use Tools | References to add the reference to Microsoft Visio X.X Type Library. x.x depends on the version of Visio you have installed.
-
#9
Open the VBA Editor and use Tools | References to add the reference to Microsoft Visio X.X Type Library. x.x depends on the version of Visio you have installed.
Hi Phil,
Very useful example!!
I need to generate Visio Diagrams from Excelsheet as well. The excelsheet contains input and output from one node. Do you have any example which reads from excel all input node and output node and shows arrow link if it is input or output. I just need one shape diagram but arrow should refelect if it is an input or output.
Also, all the shapes should be placed at different locations on the page.
Thanks
Last edited: Jul 29, 2013
-
#10
Please provide a sample of your data including column/row references.
title | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|
About connecting to data in Visio |
visio |
2057123f-faeb-f705-5fe7-75d3b76fa1a5 |
06/08/2017 |
high |
About connecting to data in Visio
[!NOTE]
Data-connectivity features are available only to licensed users of Microsoft Visio Professional 2013.
There are four aspects of data connectivity in Visio:
-
Connecting to a data source
-
Linking shapes to data
-
Displaying linked data graphically
-
Refreshing linked data that has changed in the data source, updating linked shapes, and resolving any subsequent conflicts that may arise
Typically, you approach these aspects in the order in which they are listed; that is, you first connect your Visio drawing to a data source, then link shapes in your drawing to data in the data source, display the data in linked shapes graphically, and refresh the linked data when necessary.
Each of these aspects has new objects and members associated with it in the Visio object model. This topic deals with the first of these aspects, connecting your Visio drawing to a data source. For more information about the other aspects of data connectivity, see the following topics:
-
About Linking Shapes to Data
-
About Displaying Data Graphically
To connect your Visio drawing to a data source programmatically, you can use the Visio API for data connectivity, which includes the following objects and their associated members:
-
DataRecordsets collection
-
DataRecordset object
-
DataConnection object
-
DataRecordsetChangedEvent object
-
DataColumns collection
-
DataColumn object
About Data Recordsets and Data Connections
Each Visio Document object has a DataRecordsets collection, which is empty until you make a connection to a data source. To connect a Visio document to a data source, you add a DataRecordset object to the DataRecordsets collection of the document. A DataRecordset object in turn has a DataColumns collection of DataColumn objects, each of which is mapped to a corresponding column (field) in the data source.
Data sources you can connect to include Excel spreadsheets, Access and SQL Server databases, SharePoint lists, and other OLEDB or ODBC data sources, such as an Oracle database. When you add a DataRecordset object by connecting to one of these data sources, Visio abstracts the connection in a DataConnection object, and the DataRecordset object is said to be connected.
You can also add a DataRecordset object by using an XML file that conforms to the ADO Classic (ADO version 2.x) Data Recordset XML schema as the data source. The resulting DataRecordset object is said to be connection-less. The connection between a data source and a DataRecordset object only goes one way—from the data source to the Visio drawing. If data in the source changes, you can refresh the data in the drawing to reflect those changes. You cannot, however, make changes in the data in the drawing and then push those changes back to the data source.
Adding DataRecordset objects
To add a DataRecordset object to the DataRecordsets collection, you can use one of the following three methods, depending on the data source you want to connect to and whether you want to pass the method a connection string and query command string or a saved Office Data Connection (ODC) file that contains the connection and query information:
-
DataRecordsets.Add
-
DataRecordsets.AddFromConnectionFile
-
DataRecordsets.AddFromXML
The following Visual Basic for Applications (VBA) sample macro shows how you might use the Add method to connect a Visio drawing to data in an Excel worksheet, in this case, in the ORGDATA.XLS sample workbook that is included with Visio:
Public Sub AddDataRecordset() Dim strConnection As String Dim strCommand As String Dim strOfficePath As String Dim vsoDataRecordset As Visio.DataRecordset strOfficePath = Visio.Application.Path strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _ & "User ID=Admin;" _ & "Data Source=" + strOfficePath + "SAMPLES1033ORGDATA.XLS;" _ & "Mode=Read;" _ & "Extended Properties=""HDR=YES;IMEX=1;MaxScanRows=0;Excel 12.0;"";" _ & "Jet OLEDB:Engine Type=34;" strCommand = "SELECT * FROM [Sheet1$]" Set vsoDataRecordset = ActiveDocument.DataRecordsets.Add(strConnection, strCommand, 0, "Data") End Sub
[!NOTE]
If you run this code on non-English builds of Visio, the path to the file ORGDATA.XLS, shown here as «Samples1033ORGDATA.XLS,» will be different. Substitute the correct path for your version of Visio in your code.
The Add method returns a DataRecordset object and takes four parameters:
-
ConnectionIDOrString The ID of an existing DataConnection object or the connection string to specify a new data-source connection. If you pass the ID of an existing DataConnection object that is currently being used by one or more other data recordsets, the data recordsets become a transacted group recordset. All data recordsets in the group are refreshed whenever a data-refresh operation occurs. You can determine an appropriate connection string by first using the Data Selector Wizard in the Visio user interface (UI) to make the same connection, recording a macro while running the wizard, and then copying the connection string from the macro code.
-
CommandString The string that specifies the database table or Excel worksheet and specifies the fields (columns) within the table or worksheet that contain the data you want to query. The command string is also passed to the DataRecordset.Refresh method when the data in the recordset is refreshed.
-
AddOptions A combination of one or more values from the VisDataRecordsetAddOptions enumeration. These values specify certain data recordset behaviors, and make it possible, for example, to prevent the queried data in the recordset from appearing in the External Data window in the Visio UI or from being refreshed by user actions. Afteryou assign this value, you cannot change it for the duration of the DataRecordset object.
-
Name An optional string that gives the data recordset a display name. If you specify for data from the recordset to be displayed in the External Data window in the Visio UI, the name you pass appears on the tab of that window that corresponds to the data recordset. In our example, there is no existing data connection, so for the first parameter of the Add method, we pass strConnection, the connection string we defined. For the second parameter, we pass strCommand, the command string we defined, which directs Visio to select all columns from the worksheet we specified. For the third parameter of the Add method, we pass zero to specify default behavior of the data recordset, and for the last parameter, we pass Org Data, the display name we defined for the data recordset.
The following sample code shows how to get the DataConnection object that was created when we added a DataRecordset object to the DataRecordsets collection. It prints the connection string associated with the DataConnection object in the Immediate window by accessing the ConnectionString property of the DataConnection object.
Public Sub GetDataConnectionObject(vsoDataRecordset As Visio.DataRecordset) Dim vsoDataConnection As DataConnection Set vsoDataConnection = vsoDataRecordset.DataConnection Debug.Print vsoDataConnection.ConnectionString End Sub
Just as you can get the connection string associated with a DataConnection object by accessing its ConnectionString property, you can get the command string associated with a DataRecordset object by accessing its CommandString property. Both of these properties are assignable, so you can change the data source associated with a DataRecordset object or the query associated with a DataConnection object at any time, although changes are not reflected in your drawing until you refresh the data. For more information about refreshing data, see About Linking Shapes to Data.
Accessing data in Data Recordsets programmatically
When you import data, Visio assigns integer row IDs, starting with the number 1, to each data row in the resulting data recordset, based upon the order of rows in the original data source. Visio uses data row IDs to track the rows when they are linked to shapes and when data is refreshed. If you want to access data rows programmatically, you must use these data row IDs. For information about how data-refresh operations affect row order, see About Linking Shapes to Data.
Use the DataRecordset.GetDataRowIDs method to get an array of the IDs of all the rows in a data recordset, where each row represents a single data record. The GetDataRowIDs method takes as its parameter a criteria string, which is a string that conforms to the guidelines specified in the ActiveX Data Object (ADO) API for setting the ADO.Filter property. By specifying appropriate criteria and using AND and OR operators to separate clauses, you can filter the information in the data recordset to return only certain data recordset rows selectively. To apply no filter (that is, to get all the rows), pass an empty string («»). For more information about criteria strings, see the Filter Property topic in the ADO 2.x API Reference. After you retrieve the data-row IDs, you can use the DataRecordset.GetRowData method to get all the data stored in each column in the data row. For more information about data columns, see About Linking Shapes to Data.
The following sample code shows how to use the GetDataRowIDs and GetRowData methods to return the row ID of each row and then get the data stored in each column in every row of the data recordset passed in. It uses two nested For…Next loops to iterate through all the rows in the recordset and then, for each row, iterate through all the columns in that row. The code displays the information returned in the Immediate window. Note that you pass an empty string to the GetDataRowIDs method to bypass filtering and get all the rows in the recordset. After you call the procedure, note that the first set of data shown (corresponding to the first data row) contains the headings for all the data columns in the data recordset.
Public Sub GetDataRecords(vsoDataRecordset As Visio.DataRecordset) Dim lngRowIDs() As Long Dim lngRow As Long Dim lngColumn As Long Dim varRowData As Variant 'Get the row IDs of all the rows in the recordset lngRowIDs = vsoDataRecordset.GetDataRowIDs("") 'Iterate through all the records in the recordset. For lngRow = LBound(lngRowIDs) To UBound(lngRowIDs) varRowData = vsoDataRecordset.GetRowData(lngRow) 'Print a separator between rows Debug.Print "------------------------------" 'Print the data stored in each column of a particular data row. For lngColumn = LBound(varRowData) To UBound(varRowData) Debug.Print vsoDataRecordset.DataColumns(lngColumn + 1).Name _ & Trim(Str(lngColumn)) & " = " & VarRowData(lngColumn) Next lngColumn Next lngRow End Sub
[!includeSupport and feedback]
I work a lot with layers in Visio, and written an add-in, LayerManager, to assist, but I was asked an interesting question recently: How can shapes by assigned to layers automatically from a list in Excel? So, I thought I would present my solution. This particular request was for a Timeline diagram, where the Milestone shapes are to be on specific layers. So, I just used one of the samples provided with Visio.
The first part of solution is to get a list in Excel which can be used to identify the shapes, and to add a column with the desired layer name for each shape, if such a column does not exist already.
Fortunately, the Shape Reports feature in Visio can export a list of shapes to Excel. This tool can export many shape properties and any of the Shape Data that are on the shapes too.
If the report is exported to Excel, it will contain a top row with the title, then the second row contains the column headers, with all of the data below it. Fortunately, Power Query has great abilities, including promoting row values to become the column headers, and transforming text into dates. I decided to add a MonthName column to use as the names of layers in Visio.
So, I now have a table in Excel which has a column with the ID of each shape, and another column that I want to be the name of a layer that the shape needs to be assigned to.
Now I needed a VBA macro to read the active Excel table, and assign the layer to each shape in the active Visio page.
I normally but VBA code in stencils so they can be re-usable with any document. The following code also requires that the Microsoft Excel Object library.
The VBA code is offered below with minimal error trapping:
Option Explicit
Public Sub AssignLayersFromTable()
Dim title As String
title = "AssignLayersFromTable"
On Error GoTo errHandler
Dim excelApp As Excel.Application
Dim sourceWrkbk As Excel.Workbook
Dim sourceWrksht As Excel.Worksheet
Dim sourceTable As Excel.ListObject
Set excelApp = GetExcelApp()
If excelApp Is Nothing Then
GoTo exitHere
End If
Set sourceWrkbk = excelApp.ActiveWorkbook
If sourceWrkbk Is Nothing Then
GoTo exitHere
End If
Set sourceWrksht = excelApp.ActiveSheet
If sourceWrksht Is Nothing Then
GoTo exitHere
End If
Debug.Print sourceWrksht.Name
If sourceWrksht.ListObjects.Count > 0 Then
Set sourceTable = sourceWrksht.ListObjects.Item(1)
End If
Dim listCol As ListColumn
Dim listRow As listRow
Dim msg As String
If Not sourceTable Is Nothing Then
Debug.Print sourceTable.Name
msg = ""
For Each listCol In sourceTable.ListColumns
msg = msg & vbCrLf & listCol.Index & vbTab & listCol.Name
Debug.Print listCol.Index, listCol.Name
Next
Dim retValue As Variant
Dim colShape As Integer
Dim colLayer As Integer
retValue = InputBox(msg, "Enter the number of the shape ID column")
If Not IsNumeric(retValue) Then
MsgBox "Sorry, that was not a number", vbExclamation, title
GoTo exitHere
End If
colShape = CInt(retValue)
If colShape < 1 Or colShape > sourceTable.ListColumns.Count Then
MsgBox "Sorry, the number must be in the range", vbExclamation, title
GoTo exitHere
End If
retValue = InputBox(msg, "Enter the number of the layer name column")
If Not IsNumeric(retValue) Then
MsgBox "Sorry, that was not a number", vbExclamation, title
GoTo exitHere
End If
colLayer = CInt(retValue)
If colLayer < 1 Or colLayer > sourceTable.ListColumns.Count Then
MsgBox "Sorry, the number must be in the range", vbExclamation, title
GoTo exitHere
End If
Dim shp As Visio.Shape
Dim iLyr As Integer
Dim lyr As Visio.Layer
For Each listRow In sourceTable.ListRows
Set shp = ActivePage.Shapes.ItemFromID(listRow.Range(1, colShape))
If Not LayerExists(ActivePage, listRow.Range(1, colLayer).Value) Then
ActivePage.Layers.Add listRow.Range(1, colLayer).Value
End If
'Remove all assigned layers
For i = shp.LayerCount To 1 Step -1
Set lyr = shp.Layer(i)
lyr.Remove shp, 0
Next
Set lyr = ActivePage.Layers(listRow.Range(1, colLayer).Value)
'Assign to the desired layer
lyr.Add shp, 0
Next
End If
exitHere:
Set sourceTable = Nothing
Set sourceWrksht = Nothing
Set sourceWrkbk = Nothing
Set excelApp = Nothing
Exit Sub
errHandler:
MsgBox Err.Description, vbCritical, "AssignLayersFromTable"
Resume exitHere
End Sub
Private Function IsOnLayer(ByVal shp As Visio.Shape, ByVal lyrName As String)
End Function
Private Function LayerExists(ByVal pag As Visio.Page, lyrName As String) As Boolean
Dim lyr As Visio.Layer
For Each lyr In pag.Layers
If lyr.Name = lyrName Or lyr.NameU = lyrName Then
LayerExists = True
End If
Next
LayerExists = False
End Function
Private Function GetExcelApp() As Excel.Application
On Error Resume Next
Set GetExcelApp = GetObject(, "Excel.Application")
End Function
I hope this helps….
A French user of LayerManager recently reported that the Refresh Counts button was not working for him, and a few other users were recently finding that the trial period was reporting expired immediately after download. Both of these issues have hopefully been addressed in the latest version 23.3.1, which is available for free to current…
Continue Reading Update to LayerManager add-in for non-English users
Regular readers of my blog will know that I like to use the Data Visualizer (DV) in Visio Plan 2, but I recently tried to help a user who really decided to push it to the limits. In this scenario, there were multiple connections, but with different labels, being created between the same flowchart shapes,…
Continue Reading Pushing Data Visualizer in Visio to the limits!
Desktop Visio has a tremendous ability to assign shapes to none, one or more layers, and the efficient use of them can make a drawing so powerful by toggling layers visibility or locking certain layers whilst working on other layers. The same drawing can be used, displayed or printed for many different purposes just by…
Continue Reading Editing Visio Layer Colours with LayerManager
I was preparing a new update of my Layer Manager tool, and was constantly coming across a lack of quality control in the sub-shape layer assignment in a number of the master shapes in Microsoft provided stencils. I have mentioned this to Microsoft as a bug before but the problem still persists in Visio for…
Continue Reading Fixing the sub-shape layer assignments of Visio shapes
I have had more than one person ask me how to see the full Layer Manager panel, so I must have not made it clear enough in the help file. Visio has a Developer Mode that is simple to switch on, and provides some extra functionality, including a Developer tab in the ribbon. Layer Manager…
Continue Reading Developer Mode for advanced Layer Manager actions
Back in 2012, my fellow Visio MVPs, Scott Helmers and Chris Roth, and I recorded a series of 24 videos about Visio 2010. They were first hosted on Microsoft’s web site, then they put them up on YouTube, they they got deleted :-(. Well, we have managed to retrieve them, and put them back up…
Continue Reading Visio 2010 MVP Session videos reprise
0 / 0 / 0 Регистрация: 13.07.2012 Сообщений: 23 |
|
1 |
|
08.11.2012, 10:24. Показов 5164. Ответов 9
Есть задача запустить из макроса в Excel Visio, загрузить файл vsd и запустить макрос из файла vsd.
0 |
Заблокирован |
||||
08.11.2012, 15:06 |
2 |
|||
Сообщение было отмечено как решение РешениеAlexPortnow, никогда с Visio не сталкивался — наковырял из разных источников.
3 |
0 / 0 / 0 Регистрация: 13.07.2012 Сообщений: 23 |
|
08.11.2012, 15:12 [ТС] |
3 |
не пашет..(((
0 |
Заблокирован |
|
08.11.2012, 15:15 |
4 |
не пашет..((( Слишком красноречиво!
0 |
Модератор 34706 / 19227 / 4039 Регистрация: 12.02.2012 Сообщений: 32,183 Записей в блоге: 13 |
|
08.11.2012, 15:17 |
5 |
не пашет..((( — у меня нет Visio. Покажите скриншот проблемы.
0 |
AlexPortnow 0 / 0 / 0 Регистрация: 13.07.2012 Сообщений: 23 |
||||||||
08.11.2012, 15:28 [ТС] |
6 |
|||||||
Материться на строки
Добавлено через 9 минут Добавлено через 1 минуту
0 |
Заблокирован |
||||||||
08.11.2012, 15:29 |
7 |
|||||||
А так?
6-я строка
Open замени на OpenEx
1 |
0 / 0 / 0 Регистрация: 13.07.2012 Сообщений: 23 |
|
08.11.2012, 16:21 [ТС] |
8 |
нет, результат тотже Добавлено через 8 минут Добавлено через 1 минуту Добавлено через 36 секунд Добавлено через 34 минуты
0 |
Казанский 15136 / 6410 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
||||
08.11.2012, 22:19 |
9 |
|||
appVisio.open «файл.vsd» Наверно, так:
2 |
0 / 0 / 0 Регистрация: 13.07.2012 Сообщений: 23 |
|
09.11.2012, 08:46 [ТС] |
10 |
да точно
0 |