Word docvariable как изменить
У меня есть документ с некоторыми переменными документа, и я пытаюсь использовать эти переменные в документе. Но так как переменные устанавливаются внешней системой (что не очень хорошо задокументировано), я играю в догадки. Я предполагаю, что существует переменная с «последней датой ревизии», и затем начинаю угадывать, как эта переменная могла быть вызвана.
Есть ли способ перечислить все переменные документа в документе MS Word и их значения, чтобы их можно было искать при использовании их в документе? (Я работаю над MS Office 2010)
В Word есть несколько различных типов «переменных». Есть вещи, известные как «переменные документа», но есть и другие вещи, которые я буду называть «свойствами» - я постараюсь перечислить основные типы ниже.
В Word есть несколько мест, где вы можете найти некоторые типы свойств, но для истинных «переменных» и других типов свойств, если вы не можете использовать макросы или другой код, вам нужно будет разархивировать файл .docx и посмотрите на различные файлы там.
Места, которые вы можете посмотреть в Word 2010 (здесь не отображаются переменные документа) .
а. В «Backstage» - посмотрите на вкладку «File», «Info», и вы увидите некоторые свойства, перечисленные справа. Нажмите «Показать все свойства» в нижней части списка, и вы можете увидеть больше.
б. На вкладке Вставка, группа Текст, Быстрые детали-> Свойства вы должны увидеть список «Встроенные свойства + некоторые или все свойства, вставленные Sharepoint, если это то, что вы используете.
с. В «Информационной панели документа» (DIP). Если вы этого не видите, перейдите в меню «Файл», затем «Параметры», а затем, скажем, «Панель быстрого доступа». Выберите «Выбрать команды» в разделе «Все команды», затем найдите «Свойства», выберите его и нажмите кнопку «Добавить». Вы должны увидеть значок на панели быстрого доступа, который имеет маленькое белое «i» на круглом синем фоне. Нажмите на нее, и вы увидите либо некоторые встроенные свойства (Автор, Заголовок и т. Д.), Либо некоторые свойства «Тип контента» Sharepoint, если вы используете SharePoint. Вы можете переключаться между одним из нескольких представлений. Если затем щелкнуть раскрывающийся список в верхнем левом углу DIP и выбрать «Дополнительные свойства», вы увидите диалоговое окно с несколькими вкладками, в котором отображается
некоторые "встроенные" свойства
"пользовательские" свойства старого стиля "Пользовательский".
Для всего остального вам, вероятно, придется искать в XML в .docx. Для этого сделайте копию вашего документа. Допустим, копия называется mydoc.docx. Переименуйте его в mydoc.docx.zip, откройте zip, затем найдите несколько вещей, как предложено ниже .
а. Истинные переменные документа хранятся в папке word, в файле settings.xml, в элементе с именем w: docVars. Вы должны увидеть имя и значение для каждой переменной. Вы можете вставить значения переменных документа в ваш документ, используя поле .
б. Встроенные свойства документа, в том числе такие, как автор, заголовок и т. Д. В большинстве случаев значения могут быть вставлены в документ с использованием специальных полей, таких как или, в некоторых случаях, полей . Хотя это немного грязно, есть стандартный список имен. Вы можете найти большинство значений в папке docProps в файлах core.xml и app.xml. Однако некоторые («Свойства титульной страницы»), если они используются, хранятся в одном из файлов «item.xml» (например, «item1.xml» в папке customXml).
с. «определяемые пользователем» пользовательские свойства старого стиля, которые состоят в основном из пар имя / значение, значения которых можно вставить в документ с помощью полей , например, . Они отображаются в диалоговом окне Дополнительные свойства . но в .docx они находятся в файле custom.xml в папке docProps.
д. пользовательские свойства нового стиля, также известные как «свойства Sharepoint» или «свойства типа содержимого», поскольку они часто создаются и заполняются из столбцов в списке Sharepoint. Значения хранятся в «Пользовательских частях XML» и могут быть вставлены с использованием элементов управления контентом, которые были настроены так, чтобы указывать на соответствующий бит XML. (Только Word 2007 и более поздние версии). В .docx вы найдете несколько «схем» для этих переменных и значения переменных в папке customXML, в файлах с именем «item1.xml», «item2.xml» и т. Д.
е. наконец, любой разработчик может поместить свои собственные пользовательские части XML в документ Word и подключить элементы управления контентом к элементам и атрибутам в этих пользовательских частях XML. Я не буду пытаться вдаваться в детали того, как это делается, но вы найдете данные в файлах item1.xml, item2.xml и т. Д. В customXML. Однако, чтобы найти сами элементы управления контентом, их имена и то, с чем они связаны, вам, как правило, нужно искать в папке word, например, document.xml, и, возможно, один или несколько из «header» и «footer». XML-файлы.
Отличный ответ. Спасибо! Одно примечание: «б. На вкладке« Вставка »,« Текстовая группа »,« Быстрые детали-> Свойства », вы должны увидеть список« Встроенные свойства + некоторые или все свойства, вставленные Sharepoint, если это то, что вы используете ». В моей настройке У Quick Parts, похоже, нет «Свойства»
Свойства и DocVariables выглядят довольно похоже на то, как вы можете использовать их в полях слов и VBA. Есть ли компромиссы?
У меня была похожая проблема. Произошел сбой какого-то стороннего набора инструментов, и мне нужно было установить значение переменной.
Это немного грубо, но вот некоторый код VBA, который я добавил, который перечислит все переменные в ActiveDocument.Variables коллекции;
Вы можете создать новый макрос и выбросить его туда, который должен дать вам информацию. Найдя имя интересующей вас переменной, вы можете установить его с помощью
Это довольно круто, спасибо. Очень жаль, что Microsoft не предоставила предварительно упакованное окно выбора вида, которое вы предоставляете ему коллекцию, и у вас появляется всплывающее окно с двумя столбцами, которое позволяет выбрать один или несколько элементов из коллекции (или добавить новое значение в фактической коллекции), а затем позволяет вашему коду VBA получить доступ к выбранным элементам в вызывающей подпрограмме / функции.
Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.
For more information about how to use the sample code in this article, click the article number below to view the article in the Microsoft Knowledge Base:
290140 OFFXP: How to Run Sample Code from Knowledge Base Articles
You can use the Microsoft Visual Basic for Applications Variables collection to set and retrieve the contents of a string variable in a Word document or template.
Also, you can use the DocVariable field to retrieve the value of a document variable after it has been set to display within a Word document.
How to Set and Retrieve the Value of a Document Variable
The following sample macro uses the Variables property to store and then retrieve the value of a string variable named "FullName" with the current document.
NOTE: The following error message appears if the Variable name is already set in the document:
Run-Time Error "5903": The Variable name already exists.
You must delete the name or just reset the value argument.
How to Delete a Document Variable
The following sample macro uses the Variables property to first set and retrieve the value of a document variable and then delete the variable from the active document.
How to Retrieve the Value of a Document Variable by Using the DocVariable Field
The following sample macro uses the Variables property to set a document variable. Following the sample macro are steps to use the DocVariable field to retrieve the value into the contents of the same document.
To use the DocVariable field, follow these steps:
On the Insert menu, click Field.
Note In Microsoft Office Word 2007, click Quick Parts in the Text group on the Insert tab, and then click Field.
In the Categories box, select Document Automation.
In the Field names list, select DocVariable.
In the New Name box, under Field properties, type the name of the document variable.
NOTE: If you see Advanced field properties instead of
Field properties, click Hide Codes.
If you need to preserve a value between sessions of a macro, you can store values by using any of the following methods:
Use the PrivateProfileString property to store values to a private settings file.
For more information about the PrivateProfileString property, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type PrivateProfileString Property in the Office Assistant or the Answer Wizard, and then click Search to view the topic.
Use the Variables property to store values in a document.
For more information about the Variables property, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type Variables property in the Office Assistant or the Answer Wizard, and then click Search to view the topic.
Use the Visual Basic for Applications Input/Output statements to write to a text file (for example, a Write statement or Print statement).
For more information about writing data to files, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type writing data to files in the Office Assistant or the Answer Wizard, and then click Search to view the topic.
Use the AutoTextEntry object to store values in an AutoText entry.
For more information about the AutoTextEntry object, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type AutoTextEntry object in the Office Assistant or the Answer Wizard, and then click Search to view the topic.
Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.
For more information about how to use the sample code in this article, click the article number below to view the article in the Microsoft Knowledge Base:
290140 OFFXP: How to Run Sample Code from Knowledge Base Articles
You can use the Microsoft Visual Basic for Applications Variables collection to set and retrieve the contents of a string variable in a Word document or template.
Also, you can use the DocVariable field to retrieve the value of a document variable after it has been set to display within a Word document.
How to Set and Retrieve the Value of a Document Variable
The following sample macro uses the Variables property to store and then retrieve the value of a string variable named "FullName" with the current document.
NOTE: The following error message appears if the Variable name is already set in the document:
Run-Time Error "5903": The Variable name already exists.
You must delete the name or just reset the value argument.
How to Delete a Document Variable
The following sample macro uses the Variables property to first set and retrieve the value of a document variable and then delete the variable from the active document.
How to Retrieve the Value of a Document Variable by Using the DocVariable Field
The following sample macro uses the Variables property to set a document variable. Following the sample macro are steps to use the DocVariable field to retrieve the value into the contents of the same document.
To use the DocVariable field, follow these steps:
On the Insert menu, click Field.
Note In Microsoft Office Word 2007, click Quick Parts in the Text group on the Insert tab, and then click Field.
In the Categories box, select Document Automation.
In the Field names list, select DocVariable.
In the New Name box, under Field properties, type the name of the document variable.
NOTE: If you see Advanced field properties instead of
Field properties, click Hide Codes.
If you need to preserve a value between sessions of a macro, you can store values by using any of the following methods:
Use the PrivateProfileString property to store values to a private settings file.
For more information about the PrivateProfileString property, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type PrivateProfileString Property in the Office Assistant or the Answer Wizard, and then click Search to view the topic.
Use the Variables property to store values in a document.
For more information about the Variables property, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type Variables property in the Office Assistant or the Answer Wizard, and then click Search to view the topic.
Use the Visual Basic for Applications Input/Output statements to write to a text file (for example, a Write statement or Print statement).
For more information about writing data to files, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type writing data to files in the Office Assistant or the Answer Wizard, and then click Search to view the topic.
Use the AutoTextEntry object to store values in an AutoText entry.
For more information about the AutoTextEntry object, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type AutoTextEntry object in the Office Assistant or the Answer Wizard, and then click Search to view the topic.
where the document variables are located in a word document . How can we see the created documented variables in a word document.
All replies
You mean, how can the content of a document variable stored in the document be displayed to the user, as part of the document text?
Insert a DocVariable field that references the name of the document variable.
It's not clear to me whether you want code (and in what programming language) or the steps for the end-user?
Cindy Meister, VSTO/Word MVP
i have created code to insert a document variable but i dont know how to view the created document variable. i donot need the code ,i need the procedure for word 2007 to view the already created document variables.
Position the cursor where you want to see the content of the Document variable.
Press Ctrl+F9 to insert a pair of
Within the braces type: DocVariable
Type the name of the document variable.
Press F9 to update the DocVariable field. (This should also toggle the code view to the display view. Alt+F9 will always toggle the view of all fields in a document between the code and display views.)
Cindy Meister, VSTO/Word MVP
i have created a document variable already but if i press Alt+F9 it is not showing that.. is there anyother way to view those document variables that has been already created
Creating a Document Variable in the document is one thing. Creating a DocVariable field in the document is something entirely different. Alt + F9 will not show the document variable, only field codes/field results.
You must first insert a field code (using the steps I gave you), then update it (F9), then toggle it until you get the field results in place of the field codes (Alt+F9).
By design, there is absolutely no option in the UI to edit the contents of document Variables and they can only be displayed using a DocVariable field.
Cindy Meister, VSTO/Word MVP
public static void EmbedVariable(Word.Document doc, string msg)
// Remove existing variables just in case.
foreach (Word.Variable v in doc.Variables)
if (v.Name.StartsWith(DOC_VARIABLE_PREFIX))
v.Delete();
>
>
// Maybe use System.IO.StringReader?
int count = ((msg.Length - 1) / PARTITION) + 1;
for (int i = 0; i < count; ++i)
object s = msg.Substring(
i * PARTITION,
i < count - 1 ? PARTITION : msg.Length - i * PARTITION);
//public string Substring(int startIndex,int length)
//substring(0,60000)
doc.Variables.Add(DOC_VARIABLE_PREFIX + i.ToString(), ref s);
//doc.Variables.Add(name,value);
>
>
sir this is the part of my name which inserts a document variables with the specified prefix given in DOC_VARIABLE_PREFIX variable.
i stored a signature of a hashed value in that document variable . But i dont know how to see the stored value of that document variable.i need it for word 2007.
in word 2003 i tried to insert a sample field which was already created by me using the option insert->field. and then i pressed Alt+F9 . It showed the content of the document variable.
whether i should follow the same procedure for my above application also.? if so how should i view in word 2007
Как правильно вставить переменную в документ word? чтоб потом к ней можно было обращаться из программ VBA и макросов Excel в том числе.
как организовать такое обращение?
скорее всего что это одно и то же, те же яйца вид сбоку.
как с ними работать?
т.е.
wDoc = GetObject("mywrod.doc")
1. дальше хочу получить список всех переменных (закладок, docavriable или чего то еще)
2. присвоить им свои значения
3. отобразить все это добро
п.с. с дельфями работал года 3 назад, а под офис вообще ничего не писал. вот осваиваю смежные специальности
речь про DOCVARIABLES("имя") .
1. как их поместить в документ в нужное место?
2. как этим переменным задать значение при обращении из excel'я?
упс.. просмотрел реализацию (чужая) это они там так закладки назвали.
можно просто добавить закладку через Вставка/Закладка обращение к ней
ActiveDocument.Bookmarks("имязакладки").Range.Text = "qweqweqwe"
Не смешивайте!
Закладки, Поля и Переменные документа - это три совершенно разные вещи!
Опишите подробнее, что нужно.
Текст должен быть виден в документе? Изменять его сожержимое из макроса надо?
есть шаблон документа, в который хочется подставлять данные из Excel строго в определенные участки документа.
Например: ФИО первой строкой, общая сумма последней, и т.д.
Я делал так (пользовался формами).
1. MSWord -> RClick на панелях инструментов Ворда -> "Формы" (чтобы отобразить панель инструментов "Формы")
2. На панели инструментов "Формы" - LClick "Текстовое поле" -> В документе появится текстовое поле (серенькое, если затенение полей формы включено)
3. RClick на появившемся поле в документе -> Свойства
4. В окне "Параменты текстового поля" -> "Параменты поля/Закладка:" вводим, например, "MyTextField1" -> ОК
5. В текстовом поле документа (сереньком) вводим какой-нибудь текст, например, "QWERTY"
6. В ВБА (Alt+F11) -> пишем:
7. F5 на макросе и видим на экране "QWERTY" ! Или "ЙЦУКЕН", как у меня, что в общем-то тоже радует глаз!
Пойдёт? Извиняюсь, что так подробно, вдруг всё-таки кто-ньть читать будет
Читайте также: