Позиция текста в word vba

Добрый день, готов с вами пообщаться по скайпу, когда вам будет удобно.
И высылаю тестовый пример, где все уже отражено.
Итак — есть вордовский документ, в котором в определенные места необходимо вставить текст, это чаще всего ФИО.
Или клише подписи, содержащее ФИО. Поэтому необходимо уметь вставить и текст и графический файл.
Я вставил в текст документа метки “!|” – это метка для вставки текста. (ФИО)
“(|” – это метка для вставки графического файла и это может быть клише содержащее ФИО.
Эти метки могут быть вставлены как просто в тексте документа, так и в поля таблиц, которые есть в документе.
Документ может содержать одну и более страниц. На каждой странице, кроме

последне

й нужно заполнять Нижний колонтитул. Ну для этого скорее всего можно просто сделать раздел и отдельно колонтитул для последней страницы, ну или реализовать кодом.
В тестовом примере показаны варианты Нижнего колонтитула: в Нижний колонтитул нужно уметь вставлять ТЕКСТ и графический файл (клише).
Кроме того, в нижним колонтитуле может быть таблица, поэтому нужно уметь вставлять ТЕКС и графический файл(клише) в
Поля этой таблицы. В высылаемом примере – это все визуализировано.

В сам документ вставлены таблицы, а в ячейки таблиц ПОЛЯ. Кроме того поля могут быть вставлены просто в текст документа.
Если документ закрыть паролем, то есть возможность вносить данные только в эти ПОЛЯ. Таблицы и поля заполняются вручную. Это номер документа и дата и еще какие-то могут быть данные. Это скорее пишу просто для информации, так как не нужно автоматизировать заполнение полей данными из других источников-файлов.
Я представляю сам процесс следующим образом – сделать вордовский файл, в нем вывести форму и несколько кнопок управления и запуска кода, который сейчас вырысовывается. И с этой формы запускать код для обработки файлов-документов, который будут лежать в определенной папке. С этим никаких трудностей нет. Сейчас нужно добиться прогресса с нижним колонтитулом.

В документах не нашел разрывы на разделы.

Все это в рамках борьбы с трудностями с наличием бумаги A4

I aim to replace a certain text in a ms word document with a textbox. This textbox needs to have the replaced text in it. The textbox should appear at the same position like the replaced text and the following content must wrap around the textbox.

With the following code I can accomplish the replacement of the text with a textbox and with the replaced text in the textbox, but the textbox is always at the same place.

What I need now, is the possibility to get the position of a found text to use it for the textbox to replace the found text. :)

My code snippet:

positionLeft = 50  /* here I need the left position of the found text */
positionTop = 50   /* and here the top position */

With ActiveDocument.Range.find
            .Forward = True
            .Wrap = wdFindStop
            .Text = TextToReplace
            .Execute
            If .Found = True Then
                Dim Box As Shape
                Set Box = ActiveDocument.Shapes.AddTextbox(msoTextOrientationHorizontal, positionToLeft, positionToRight, 100, 100)
                Box.TextFrame.textRange.Text = TextToReplace
                .Parent = ""
            End If
End With

Is it even possible to get the absolute left and top position of a text in the word document? And if yes, how can i get this done?

I want to access the position and size for each indivisible unit in Microsoft Word. Examples of such units include individual characters, images, etc.

The purpose is to apply a visual overlay based on unit position and size. I will have no knowledge of the content in target documents.

Imagine the text of this question in a word document. I need to be able to iterate each character including white-space and carriage returns and get the size and position.

EDIT
It doesn’t matter whether your answer considers macros, interop, add-ins or OLE embedding.

Berkay Turancı's user avatar

asked Apr 15, 2012 at 20:35

Raheel Khan's user avatar

Raheel KhanRaheel Khan

14.1k13 gold badges78 silver badges167 bronze badges

The method which retrieves displayed coordinates of an object is Window.GetPoint (link for the office interop version, same thing in VBA).

As for the «indivisible unit,» you can put any meaning you want into that, using the available collections.
For instance, if you want it to be characters, you can use Document.Range.Characters, which is a collection of characters, each of which is a Range.
Or you can use Document.Range.InlineShapes for the pictures that are part of text.
Or Document.Range.ShapeRange to enumerate «floating» shapes.

At which point you might be thinking about Window.RangeFromPoint to figure an object from its window coordinates.

answered Apr 15, 2012 at 21:12

GSerg's user avatar

1

Suppose i have a string separated by spaces/hyphens.

Eg. Take these broken wings and learn to fly.

What vba function can find the position of the word broken which should be returned as 3, not 11 which is the character position.

asked Aug 2, 2013 at 8:45

SanilB's user avatar

One solution (there probably is a more efficient way) would be to split the string and iterate over the returned array:

Function wordPosition(sentence As String, searchWord As String) As Long

    Dim words As Variant
    Dim i As Long

    words = Split(sentence, " ")
    For i = LBound(words, 1) To UBound(words, 1)
        If words(i) = searchWord Then Exit For
    Next i

    'return -1 if not found
    wordPosition = IIf(i > UBound(words, 1), -1, i + 1)

End Function

You can call it ilke this:

Sub AnExample()

    Dim s As String
    Dim sought As String

    s = "Take these broken wings and learn to fly"
    sought = "broken"

    MsgBox sought & " is in position " & wordPosition(s, sought)

End Sub

answered Aug 2, 2013 at 8:54

assylias's user avatar

assyliasassylias

319k78 gold badges658 silver badges776 bronze badges

4

The solution proposed by assylias is pretty good and just need a small adaptation to account for multiple occurrences:

Function wordPosition(sentence As String, searchWord As String) As Long()

    Dim words As Variant
    Dim i As Long

    words = Split(sentence, " ")
    Dim matchesCount As Long: matchesCount = 0
    ReDim matchesArray(UBound(words) + 1) As Long
    For i = LBound(words, 1) To UBound(words, 1)
        If words(i) = searchWord Then
           matchesCount = matchesCount + 1
           matchesArray(matchesCount) = IIf(i > UBound(words, 1), -1, i + 1)
        End If
    Next i

    If (matchesCount > 0) Then
       matchesArray(0) = matchesCount
    End If

    wordPosition = matchesArray

End Function


Sub AnExample()

    Dim s As String
    Dim sought As String

    s = "Take these broken wings and learn to fly and broken again"
    sought = "broken"

    Dim matches() As Long: matches = wordPosition(s, sought)

    If (matches(0) > 0) Then
       Dim count As Integer: count = 0
       Do
          count = count + 1
          MsgBox "Match No. " & count & " for " & sought & " is in position " & matches(count)
       Loop While (count < matches(0))

    End If

End Sub

answered Aug 2, 2013 at 10:28

varocarbas's user avatar

varocarbasvarocarbas

12.4k4 gold badges25 silver badges37 bronze badges

Я пытаюсь написать программу на VBA, которая записывает некоторый текст в документ Word, я хочу, чтобы когда текст попал на определенное расстояние от левой стороны документа, он распечатал оставшиеся символы до следующего полного остановить, а затем начать новую строку и табуляцию для каждого символа в строке. Это пример того, что должно произойти:

Код, который у меня ниже, работает правильно на первой странице слова, но на дополнительных страницах он начинает распечатывать случайным образом, и значение, указанное из objSelection.range.Information(WdInformation.wdHorizontalPositionRelativeToPage) кажется, причина проблемы.

Пример некорректного вывода в word:

Несколько вещей, которые я заметил, пытаясь решить эту проблему:

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

Если у меня установлено приложение word, которое не отображается с самого начала, оно не работает каждый раз после первой страницы

Если у меня слово приложение установлено как видимое, оно работает правильно на каждой странице, пока я не щелкну где-нибудь на экране за пределами слова приложение.

Это код, который у меня есть:

Sub print_to_word()
        '**** SETTING UP WORD *****
        Dim wordApp As Word.Application
        On Error Resume Next
        Set wordApp = GetObject(, "Word.Application")
        If wordApp Is Nothing Then   'if word is not open then open it
            Set wordApp = CreateObject("Word.Application")
        End If
        On Error GoTo 0 'reset error warnings
        Dim objdoc As Document
        Set objdoc = wordApp.Documents.Add 'Create a new word document
        Dim objSelection As Selection
        Set objSelection = wordApp.Selection 'Selection used to write text
        wordApp.Visible = True

        Dim wirecodes As String
        wirecodes = "114.114*.98.98*.99.99*.123.123*.92*.92**.92.114.114*.98.98*.99.99*.123.123*.92*.92**.92.114.114*.98.98*.99.99*.123.123*.92*.92**.92.114.114*.98.98*.99.99*.123.123*.92*.92**.92.114.114*.98.98*.99.99*.123.123*.92*.92**.92.114.114*.98.98*.99.99*.123.123*.92*.92**.92.114.114*.98.98*.99.99*.123.123*.92*.92**.92.114.114*.98.98*.99.99*.123.123*.92*.92**.92"   

        For x = 1 To 5 'print 5 lots of wirecodes
            Dim pos As Integer
            objSelection.TypeText (Chr(9)) 'tab
            For i = 1 To Len(wirecodes) 'loop through each character
                pos = objSelection.range.Information(WdInformation.wdHorizontalPositionRelativeToPage)

                If i <> 1 And pos > 215 Then 'if the cursor is past 215 then
                    Do While Mid(wirecodes, i - 1, 1) <> "." And i <> Len(wirecodes) + 1 'print out the remaining wirecode before starting a new line
                        objSelection.TypeText (Mid(wirecodes, i, 1))
                        i = i + 1
                    Loop
                    If i < Len(wirecodes) Then 'if its not the last wirecode print a newline and tab
                        objSelection.TypeText (Chr(11) + Chr(9))
                    End If
                End If
                objSelection.TypeText (Mid(wirecodes, i, 1)) 'just print the character
            Next
            objSelection.TypeText (Chr(10)) 'new line
        Next
        'close word
        objdoc.Close
        Set objdoc = Nothing
        wordApp.Quit 'close word
        Set wordApp = Nothing
End Sub

Я использую Microsoft Office 2010 в Windows 10, любая помощь будет принята с благодарностью.

Понравилась статья? Поделить с друзьями:
  • Позиция курсора word vba
  • Позиционные аргументы функций в word
  • Позиции табуляции для word
  • Позиции табуляции выставляются в ms word
  • Позиции табуляции в ms word допускают выравнивание