Vba word вставить формулу

In this article I will explain how you can create equations using VBA for word.


Step 1, Getting the Text String Associated with the Equation:

The first step for creating an equation in VBA for word is to determine the text string associated with that equation. You might not have noticed but equations in word are a basic text string. For example take a look at the the equation below:

Word Equation
If you copy the equation and paste it in a notepad this is what you get:

Word Equation in NotePad
The text in the notepad might seem like nonsense, but the word editor understands this. In order to create equations in word using VBA, we too will have the create the text string above.

The text above can be converted back to a word equation by following the steps below:

Step 1: Copy the text in the notepad editor and paste it in an empty word document:

Word, Equation Linear
Step 2: Select the text in the word document and click on the “Insert Equation” button on the “Insert” tab

Word Equation, Insert
Step 3: Choose professional View:

Word Equation Professional View
Result:

Word, Equation Professional
As you can see the equation was created from the text string in the notepad file. So basically we need to be able to generate the text string in the notepad file to create the equation in word.

I will explain this in more detail in the following sections.


Step 2:

The next step for creating an equation is to move the cursor to the location you want to insert the equation.For more information about moving the cursor around the document please see the links below:

  • Word VBA Using Bookmarks to Move the Cursor
  • Word VBA, Move Cursor to Start of Document
  • Word VBA, Move Cursor to End of Document
  • Word VBA, Move Cursor to End of Line
  • Word VBA, Move Cursor to Start of Line
  • Word VBA, Go to Specific Line


Creating Simple Equations :

Equations can be made using the code below:

Sub Example1()
Dim objRange As Range
Set objRange = Selection.Range
objRange.Text = "y = x^2+1"
Call OMaths.Add(objRange)
End Sub

Word VBA Insert Equation Restul
Note: If you want to keep reference to the newly created equation you could use the code below. You could then change the display to professional so it looks like a real equation:

Sub Example2()
Dim objRange As Range
Dim objOMath As OMath
Set objRange = Selection.Range
objRange.Text = "y = x^2+1"
Set objOMath = OMaths.Add(objRange).OMaths.Item(1)
objOMath.BuildUp
End Sub

Create equation


Creating Complex Equations:

For more complex equations you can’t simply paste the text string in the VBA editor. For example lets say we want to create the equation explained at the start of the post. The first step would be to replace the text :

  • “y = x^2+1”

with

  • “f(x)=a_0+∑_(n=1)^∞▒(a_n  cos⁡〖nπx/L〗+b_n  sin⁡〖nπx/L〗 ) “

But this is what will happen if we try to make this replacement:

Sub Example1()
Dim objRange As Range
Set objRange = Selection.Range
objRange.Text = _
"f(x)=a_0+?_(n=1)^8n(a_n  cos??npx/L?+b_n  sin??npx/L? ) "
Call OMaths.Add(objRange)
End Sub

As you can see a lot of the characters are not recognized by the VBA editor and are replaced by a “?” character. The solution to this is explained in the steps below:

Step 1: Break the text string into different segments, separating the “?” characters:

"f(x)=a_0+" + ? + "_(n=1)^8n(a_n  cos"+ ?? + _
"npx/L" + ?+ "+b_n  sin' + ?? + "npx/L" +? +" ) "

For more information about concatenating strings please see the link below:

  • VBA Excel String Processing and Manipulation

Step 2: Find the unicode value associated with the missing characters. The missing characters are:

I have written a program which returns the unicode value associated with characters. You can download the program at the link below and use it to find the unicode values associated with each of the characters above:

  • VBA Get Characters Unicode Value

Step 3: Replace the “?” characters with the ChrW() function. The ChrW() function receives as input a unicode value and returns the character associated with it:

Sub Example3()
Dim objRange As Range
Dim objOMath As OMath
Set objRange = Selection.Range
objRange.Text = _
"f(x)=a_0+" + ChrW(8721) + "_(n=1)^8" + ChrW(9618) + _
"(a_n  cos" + ChrW(12310) + "npx/L" + ChrW(12311) + _
"+b_n  sin" + ChrW(12310) + "npx/L" + ChrW(12311) + " )"
Set objOMath = OMaths.Add(objRange).OMaths.Item(1)
objOMath.BuildUp
End Sub

Result:

Word Equaton Complex
You can download the file and code related to this article from the link below:

  • Create Word Equation.docm

See also:

  • Word VBA Equations Linear/Professional Display
  • Microsoft (MSDN) OMath Object (Word)

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Cell.Formula method (Word)

vbawd10.chm156106953

vbawd10.chm156106953

word

Word.Cell.Formula

0fec018a-5a6f-f5ec-ed1c-a963e53c27b3

06/08/2017

medium

Cell.Formula method (Word)

Inserts an = (Formula) field that contains the specified formula into a table cell.

Syntax

expression.Formula (Formula, NumFormat)

expression Required. A variable that represents a ‘Cell’ object.

Parameters

Name Required/Optional Data type Description
Formula Optional Variant The mathematical formula you want the = (Formula) field to evaluate. Spreadsheet-type references to table cells are valid. For example, «=SUM(A4:C4)» specifies the first three values in the fourth row. For more information about the = (Formula) field, see Field codes:= (Formula) field.
NumFormat Optional Variant A format for the result of the = (Formula) field. For information about the types of formats you can apply, see Numeric Picture (#) field switch.

Remarks

Formula is optional as long as there is at least one cell that contains a value above or to the left of the cell that contains the insertion point. If the cells above the insertion point contain values, the inserted field is {=SUM(ABOVE)}; if the cells to the left of the insertion point contain values, the inserted field is {=SUM(LEFT)}. If both the cells above the insertion point and the cells to the left of the insertion point contain values, Microsoft Word uses the following rules to determine which SUM function to insert:

  • If the cell immediately above the insertion point contains a value, Word inserts {=SUM(ABOVE)}.

  • If the cell immediately above the insertion point doesn’t contain a value and the cell immediately to the left of it does, Word inserts {=SUM(LEFT)}.

  • If neither adjoining cell contains a value, Word inserts {=SUM(ABOVE)}.

  • If you don’t specify Formula and all the cells above and to the left of the insertion point are empty, the result of the field is an error.

Example

This example creates a 3×3 table at the beginning of the active document and then averages the numbers in the first column.

Set myRange = ActiveDocument.Range(0, 0) 
Set myTable = ActiveDocument.Tables.Add(myRange, 3, 3) 
With myTable 
 .Cell(1,1).Range.InsertAfter "100" 
 .Cell(2,1).Range.InsertAfter "50" 
 .Cell(3,1).Formula Formula:="=Average(Above)" 
End With

This example inserts a formula at the insertion point that determines the largest number in the cells above the selected cell.

Selection.Collapse Direction:=wdCollapseStart 
If Selection.Information(wdWithInTable) = True Then 
 Selection.Cells(1).Formula Formula:="=Max(Above)" 
Else 
 MsgBox "The insertion point is not in a table." 
End If

See also

Cell Object

[!includeSupport and feedback]

Hi. Помогите пожалуйста, ни как не получается вставить формулу в вордовский документ.
В VBA формула вставляется так: (формула x=1/2)

Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, PreserveFormatting:=False
Selection.TypeText Text:=»[COLOR=»Blue»]EQ x=f(1;2)[/COLOR]»
Selection.Fields.Update

Пробую на С++Buildere

Variant Word=CreateOleObject(«[COLOR=»Blue»]Word.Application[/COLOR]»);
Word.OlePropertySet(«[COLOR=»Blue»]Visible[/COLOR]»,1);
Variant Documents=Word.OlePropertyGet(«[COLOR=»Blue»]Documents[/COLOR]»);
Documents.OleProcedure(«[COLOR=»Blue»]Add[/COLOR]»);
Variant ActiveDocument=Word.OlePropertyGet(«[COLOR=»Blue»]ActiveDocument[/COLOR]»);
Variant Tables=ActiveDocument.OlePropertyGet(«[COLOR=»Blue»]Tables[/COLOR]»);
ActiveDocument.OleProcedure(«[COLOR=»Blue»]Select[/COLOR]»);
Variant Selection = Word.OlePropertyGet(«[COLOR=»Blue»]Selection[/COLOR]»);
Selection.OleProcedure(«TypeText», «[COLOR=»Blue»]EQ x=f(1;2)[/COLOR]»);

Вместо формулы вставляется текст, помогите разобраться.
Возможно есть другие возможности, советуйте!
За ранее, Спасибо!

0 / 0 / 0

Регистрация: 04.05.2013

Сообщений: 48

1

14.01.2018, 21:32. Показов 2988. Ответов 16


Студворк — интернет-сервис помощи студентам

Язык программирования Visual Basic Net.
Есть документ Word (версия с docx). В документе есть куча текста, формул, таблиц.
Как заполнять таблички — знаю.
Вопрос, как заменить определенный текст в документе и как заменить числа (или буквы) в формуле используя средства Vb.Net?

Формула любого вида (старый или новый формат).

P.s. задача, в принципе, следующая: есть програмка, которая производит расчет. Хочу при помощи кода автоматизировать вывод результатов расчета в конечный документ для пользователя. Для этого создам шаблон и в него вставлять рассчитанные значения



0



99 / 94 / 23

Регистрация: 30.08.2015

Сообщений: 457

15.01.2018, 13:21

2

Цитата
Сообщение от miki2343
Посмотреть сообщение

Для этого создам шаблон

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



0



miki2343

0 / 0 / 0

Регистрация: 04.05.2013

Сообщений: 48

15.01.2018, 17:43

 [ТС]

3

Кстати, как вариант.
Еще, кто сможет предложить способы?

Добавлено через 3 часа 41 минуту
В принципе испытал замену в новом редакторе формул. Меняет только если формула представлена в текстовом формате. Но это ничего страшного. Можно и так оставить.

Вопрос теперь в другом

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
     Dim Word As Word.Application
        Word = CreateObject("Word.Application")
        Word.Documents.Open("D:test.dotx") 'открываем документ
        Word.Visible = True
 
        With Word.Selection.Find
            .Execute(Replace("мама", 0, 0))  'что ищем
            Word.Selection.Text = "заменено" 'на что меняем
        End With
 
        With Word.Selection.Find
            .Execute(Replace("папа", 0, 0))  'что ищем
            Word.Selection.Text = "заменено1" 'на что меняем
        End With

Этот код ошибочный, а именно он меняет только одно слово «мама» на «заменено1».
Как сделать, чтобы менял «мама» на «заменено», а «папа» на «заменено1». Причем это по всему документу а не в одном месте?

Понимаю, что надо прописать ReplaceAll, но проискав по инету, выдает все ошибки в коде.



0



99 / 94 / 23

Регистрация: 30.08.2015

Сообщений: 457

15.01.2018, 17:56

4

miki2343, зачем вам Visual Basic?

Добавлено через 15 секунд
нужен же Visual Basic .NET ?



0



0 / 0 / 0

Регистрация: 04.05.2013

Сообщений: 48

15.01.2018, 18:09

 [ТС]

5

Прошу прощения — неверный тег при оформлении этого поста



0



densy

99 / 94 / 23

Регистрация: 30.08.2015

Сообщений: 457

15.01.2018, 18:10

6

Лучший ответ Сообщение было отмечено miki2343 как решение

Решение

VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Imports Microsoft.Office.Interop
 
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim oWord As Word.Application
        oWord = CreateObject("Word.Application")
        oWord.Visible = True
        oWord.Documents.Open("C:temptest.docx")
 
 
        With oWord.Selection.Find
            .Text = "папа"
            .Replacement.Text = "удалить:)"
            .Forward = True
            .Wrap = Word.WdFindWrap.wdFindContinue
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        oWord.Selection.Find.Execute(Replace:=Word.WdReplace.wdReplaceAll)
    End Sub
End Class



1



miki2343

0 / 0 / 0

Регистрация: 04.05.2013

Сообщений: 48

15.01.2018, 18:29

 [ТС]

7

Немножко Ваш код изменил, для удобства чтения в Vb.net.
Добавил вторую переменную.
Итог:

VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  Dim oWord As Word.Application
        oWord = CreateObject("Word.Application")
        oWord.Visible = True
        oWord.Documents.Open("D:test.dotx")
 
 
        With oWord.Selection.Find
            .Text = "папа"
            .Replacement.Text = "удалить:)"
        End With
        oWord.Selection.Find.Execute(Replace:=Word.WdReplace.wdReplaceAll, MatchAllWordForms:=False, MatchSoundsLike:=False, Wrap:=Word.WdFindWrap.wdFindContinue, Forward:=True, Format:=False, MatchCase:=False, MatchWholeWord:=False, MatchWildcards:=False)
 
        With oWord.Selection.Find
            .Text = "мама"
            .Replacement.Text = "кря-кря"
        End With
        oWord.Selection.Find.Execute(Replace:=Word.WdReplace.wdReplaceAll, MatchAllWordForms:=False, MatchSoundsLike:=False, Wrap:=Word.WdFindWrap.wdFindContinue, Forward:=True, Format:=False, MatchCase:=False, MatchWholeWord:=False, MatchWildcards:=False)



0



densy

99 / 94 / 23

Регистрация: 30.08.2015

Сообщений: 457

15.01.2018, 18:47

8

остается только сохранить результат

VB.NET
1
2
3
        oWord.ActiveDocument.Save()
        oWord.Quit()
        oWord = Nothing

Добавлено через 13 минут
альтернативой может служить Latex формат документа word. тенденция его использования в сапрах и математических программах — растет и нет необходимости в дополнительных инструментах для формирования документов с графиками/формул к примеру в worde



0



miki2343

0 / 0 / 0

Регистрация: 04.05.2013

Сообщений: 48

15.01.2018, 19:10

 [ТС]

9

Лучше так А то шаблон испортим

VB.NET
1
2
        oWord.ActiveDocument.SaveAs("d:Test.docx")
        oWord = Nothing

А это если еще и док закрыть (правда тогда зачем его показывать вначале))

VB.NET
1
2
3
oWord.ActiveDocument.SaveAs("d:Test.docx")
oWord.Documents.Close()
oWord.Quit()

Добавлено через 17 минут
Объединю ответ в конечный код, а то просто таких тем не мало…

Итак:
1. Добавляем в проект: Проект->Добавить ссылку-> в COM находим Microsoft Office 16 Object Library (циферка не суть). Тыкаем галочку и тыкаем ОК
2. Код:

VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Imports Microsoft.Office.Interop
Public Class Form1
 
 
 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim oWord As Word.Application
        oWord = CreateObject("Word.Application")
        oWord.Visible = True
        oWord.Documents.Open("D:test.dotx")
 
        'эта секция меняет слово "папа" на "удалить:)" ВО ВСЕМ ДОКУМЕНТЕ
        With oWord.Selection.Find
            .Text = "папа"
            .Replacement.Text = "удалить:)"
        End With
        oWord.Selection.Find.Execute(Replace:=Word.WdReplace.wdReplaceAll, MatchAllWordForms:=False, MatchSoundsLike:=False, Wrap:=Word.WdFindWrap.wdFindContinue, Forward:=True, Format:=False, MatchCase:=False, MatchWholeWord:=False, MatchWildcards:=False)
 
        'эта секция меняет слово "мама" на "кря-кря" ВО ВСЕМ ДОКУМЕНТЕ
        With oWord.Selection.Find
            .Text = "мама"
            .Replacement.Text = "кря-кря"
        End With
        oWord.Selection.Find.Execute(Replace:=Word.WdReplace.wdReplaceAll, MatchAllWordForms:=False, MatchSoundsLike:=False, Wrap:=Word.WdFindWrap.wdFindContinue, Forward:=True, Format:=False, MatchCase:=False, MatchWholeWord:=False, MatchWildcards:=False)
 
 
        'сохраняем документ с ДРУГИМ расширением, дабы не повредить шаблон
        oWord.ActiveDocument.SaveAs("d:Test.docx")
        oWord = Nothing
 
      
    End Sub
 
End Class



0



ovva

4277 / 3416 / 827

Регистрация: 02.02.2013

Сообщений: 3,305

Записей в блоге: 2

15.01.2018, 19:21

10

densy, если вы добавили ссылку на Office.Interop, то нет никакой необходимости использовать CreateObject(«Word.Application») (используется при т.н. поздней привязке).
Пример с организацией т.н. ранней привязкой:

VB.NET
1
2
3
4
5
6
7
8
9
10
Imports WRD = Microsoft.Office.Interop.Word
Public Class Form1
    Private wApp As WRD.Application
    Private wDoc As WRD.Document
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        wApp = New WRD.Application
        wDoc = wApp.Documents.Open(Path.Combine(Application.StartupPath, "tst.doc"))
        wApp.Visible = True
    End Sub
'…



1



0 / 0 / 0

Регистрация: 04.05.2013

Сообщений: 48

15.01.2018, 19:34

 [ТС]

11

Я ошибся. Неправильно указал ссылку
Надо
Microsoft Word 16.- Object Library

Office — не катит



0



0 / 0 / 0

Регистрация: 04.05.2013

Сообщений: 48

25.02.2018, 08:43

 [ТС]

12

Не хочется новую тему создавать.
А как удалить целую строку в документе?



0



Юпатов Дмитрий

1706 / 1194 / 227

Регистрация: 23.12.2010

Сообщений: 1,526

25.02.2018, 23:39

13

Цитата
Сообщение от miki2343
Посмотреть сообщение

А то шаблон испортим

а чтоб шаблон не испортить, надо не ОТКРЫВАТЬ его, а СОЗДАВАТЬ НОВЫЙ ДОКУМЕНТ на основе имеющегося файла:

VB.NET
1
wDoc = wApp.Documents.Open(Path.Combine(Application.StartupPath, "tst.doc"))

меняем на

VB.NET
1
wDoc = wApp.Documents.Add(Path.Combine(Application.StartupPath, "tst.doc"))

ну а если метод add вызвать так: add() — будет создан документ на основе шаблона по-умолчанию (обычно это Normal.dot)



0



15 / 13 / 6

Регистрация: 13.03.2013

Сообщений: 130

26.02.2018, 19:59

14

Цитата
Сообщение от miki2343
Посмотреть сообщение

Как заполнять таблички — знаю.

а можно поделиться знаниями?)))
как раз планирую решать такую задачу, не знаю с какой стороны подойти
планирую значения из DataGridView писать в docx-шаблон, в котором таблица плюс несколько текстовых строк



0



0 / 0 / 0

Регистрация: 04.05.2013

Сообщений: 48

26.02.2018, 20:07

 [ТС]

15

Заполнение таблицы Word документа — здесь есть как добавлять строки. А так полно информации по работе с Word таблицами.
Но, на мой взгляд, выше описанный способ очень неплох, т.к. создаете шаблон, а потом просто меняете в нем определенные вещи.

Или спросите более точно тогда, думаю или я или другие более грамотные ответят



0



15 / 13 / 6

Регистрация: 13.03.2013

Сообщений: 130

26.02.2018, 20:10

16

Цитата
Сообщение от miki2343
Посмотреть сообщение

Но, на мой взгляд, выше описанный способ очень неплох, т.к. создаете шаблон, а потом просто меняете в нем определенные вещи.

с заменой всё ясно
вопрос скорее как добавлять новые строки в таблицу



0



Юпатов Дмитрий

1706 / 1194 / 227

Регистрация: 23.12.2010

Сообщений: 1,526

27.02.2018, 10:19

17

Цитата
Сообщение от forlife
Посмотреть сообщение

вопрос скорее как добавлять новые строки в таблицу

Visual Basic
1
ThisDocument.Tables(1).Rows.add

это из VBA — вставляет новую строку в конец первой таблицы в документе.
https://msdn.microsoft.com/en-… ethod-word



0



Автор Илья Муромец, 16 февраля 2016, 16:51

Илья Муромец

  • гость
  • Записан

В документе есть текст и несколько уравнений (формул). Как из VBA последовательно выделить каждую формулу? Как понимаю работать надо через Selection.OMaths.Item(1), но выдается сообщение «Запрашиваемый номер семейства не существует».



Администратор

  • Administrator
  • Сообщения: 2,252
  • Записан

Создайте новый пустой ворд-файл и вставьте туда одну формулу и выложите этот файл на форуме.
Это нужно, чтобы понимать, о каких формулах вы пишите.
Или если по каким-то причинам вы не можете выложить файл, то напишите, как создаёте формулу, а именно, куда щёлкаете, чтобы вставить формулу.


Илья Муромец

  • гость
  • Записан

Вот

[вложение удалено администратором]



Администратор

  • Administrator
  • Сообщения: 2,252
  • Записан

Selection работает двумя способами:

  • если выделение в виде мигающего курсора;
  • если что-то выделено.

Используя «Selection.OMaths.Item(1)» вы говорите макросу, что хотите работать с формулами, которые находятся или рядом с курсором, или которые находятся в выделенном фрагменте.
Но в задании вы пишите, что вам нужно работать с формулами в документе, а не в выделении.
Значит используйте так:
ActiveDocument.OMaths.Item(1)


Илья Муромец

  • гость
  • Записан

Большое спасибо! Очень помогли!


  • Форум по VBA, Excel и Word

  • Word

  • Макросы в Word

  • Word VBA: работа с объектом Формула

Понравилась статья? Поделить с друзьями:
  • Vba word вставить текст после курсора
  • Vba word вставить текст в определенное место
  • Vba word вставить текст в конец документа
  • Vba word вставить рисунок за текстом
  • Vba word вставить массив