Vba word положение курсора

  • Remove From My Forums
  • Question

  • For one of my macros to run, I have to  ensure that the cursor position is not in a table or in a frame when the user activates the macro.

    How can I find our the current cursor position? Once I can determine that the cursor is positioned in a table or a frame, I can then code a message box to instruct the user where to put their cursor to run a certain routine.

Answers

  • Hi,

    Cursor position
    Selection.Range.End

    This will check whether currently in a table or frame.

        Dim lngTableCount As Long
        Dim lngFrameCount As Long

            For lngTableCount = 1 To ActiveDocument.Tables.Count
            If Selection.Range.InRange(ActiveDocument.Tables(lngTableCount).Range) Then
                MsgBox «In Table»
                Exit For
            End If
        Next

                For lngFrameCount = 1 To ActiveDocument.Frames.Count
            If Selection.Range.InRange(ActiveDocument.Frames(lngFrameCount).Range) Then
                MsgBox «In Frame»
                Exit For
            End If
        Next

I am trying to write a program in VBA which writes some text to a Word document, what I want to happen is when the text gets to a certain distance from the left side of the document it prints out the remaining characters up to the next full stop and then starts a new line and a tab for every character in the string. This is an example of what should happen:

enter image description here

The code I have below works correctly on the first page of word but on additional pages it starts to print out randomly and the value given from objSelection.range.Information(WdInformation.wdHorizontalPositionRelativeToPage) seems to be the cause the issue.

An example of the incorrect output printed to word:

enter image description here

A few things I have noticed while trying to work out this issue:

If I set a break point and step through the code one line at a time everything works fine and the correct output is printed every time.

If I have the word app set to not be visible from the start it fails every time after the first page

If I have the word app set as visible it runs correctly on every page until I click somewhere on the screen outside of the word application.

This is the code I have:

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

I’m using Microsoft office 2010 on Windows 10 any help would be greatly appreciated.

maksim_volodin

3 / 2 / 1

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

Сообщений: 33

1

02.05.2019, 07:34. Показов 5094. Ответов 5

Метки нет (Все метки)


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

Как поместить курсор в определённое место в Word.

Visual Basic
1
2
3
Sub SetStart()
  Selection.Start = 10
End Sub

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



0



Alex77755

11482 / 3773 / 677

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

Сообщений: 11,145

02.05.2019, 10:41

2

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

Решение

Visual Basic
1
2
Selection.HomeKey Unit:=wdStory
Selection.Move , 10



1



3 / 2 / 1

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

Сообщений: 33

02.05.2019, 11:10

 [ТС]

3

Я правильно понимаю, что VBA позволяет разместить курсор в определённой позиции только при условии заполнения документа до этой позиции чем-либо (символы, параграфы….)? В пустом документе передвинуть курсор нельзя.



0



11482 / 3773 / 677

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

Сообщений: 11,145

02.05.2019, 13:17

4

А куда ж его передвигать? В пустоту?
Вручную сможешь установить курсор ниже заполненной части?

Надо что-то добавлять тогда. Пробелы, параграфы …



1



Модератор

Эксперт MS Access

11341 / 4660 / 748

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

Сообщений: 13,497

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

02.05.2019, 13:23

5

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

Надо что-то добавлять тогда. Пробелы, параграфы .

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



0



11482 / 3773 / 677

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

Сообщений: 11,145

02.05.2019, 16:43

6

Галочка установлена по умолчанию.
Клик на пустом месте вставляет параграфы и отступы.



0



    msm.ru

    Нравится ресурс?

    Помоги проекту!

    Популярные разделы FAQ:    user posted image Общие вопросы    user posted image Особенности VBA-кода    user posted image Оптимизация VBA-кода    user posted image Полезные ссылки


    1. Старайтесь при создании темы указывать в заголовке или теле сообщения название офисного приложения и (желательно при работе с Office 95/97/2000) его версию. Это значительно сократит количество промежуточных вопросов.
    2. Формулируйте вопросы как можно конкретнее, вспоминая (хотя бы иногда) о правилах ВЕЛИКОГО И МОГУЧЕГО РУССКОГО ЯЗЫКА, и не забывая, что краткость — сестра таланта.
    3. Не забывайте использовать теги [сode=vba] …текст программы… [/code] для выделения текста программы подсветкой!
    4. Темы с просьбой выполнить какую-либо работу полностью за автора здесь не обсуждаются и переносятся в раздел ПОМОЩЬ СТУДЕНТАМ.

    >
    Word. Позиция курсора в строке

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    21.06.07, 07:07

      Senior Member

      ****

      Рейтинг (т): 34

      Определяю номер листа, на котором находится курсор
      Определяю номер строки
      А как определить количество символов в строке до курсора?


      coder



      Сообщ.
      #2

      ,
      21.06.07, 12:08

        ExpandedWrap disabled

          Selection.Information(wdFirstCharacterColumnNumber)


        bi-lya



        Сообщ.
        #3

        ,
        21.06.07, 12:57

          Senior Member

          ****

          Рейтинг (т): 34

          Вот ведь! Верите-нет — раз 100 сегодня это дело мимо проходил — считал, что это для таблиц. Спасибо, что ткнули носом :wub:

          Profi

          Old Bat



          Сообщ.
          #4

          ,
          21.06.07, 13:37

            Moderator

            *****

            Рейтинг (т): 128

            поправочка: Selection.Information(wdFirstCharacterColumnNumber) дает номер столбца, так что если необходимо получить кол-во символов ДО курсора, то пишем

            ExpandedWrap disabled

              Selection.Information(wdFirstCharacterColumnNumber)-1

            или используя объектную схему (на любителя)

            ExpandedWrap disabled

              ActiveDocument.Range(ActiveDocument.ActiveWindow.Panes(1).Pages(1).Rectangles(1).Lines(1).Range.Characters.First.Start, Selection.Range.End).Characters.Count


            bi-lya



            Сообщ.
            #5

            ,
            22.06.07, 04:16

              Senior Member

              ****

              Рейтинг (т): 34

              Old Bat, объектная схема — это хорошо, но для работы с переменными не совсем здорово — или я что-то не понимаю. Для того, чтобы вычислить то же кол-во символов в какой-то строке мы должны внести четыре переменных — Panes, Pages, Rectangles, Lines :wacko: :wacko: :wacko:
              Ну и ко всему я не знаю, как в этом случае определяется текущий Rectangles — все остальное знаю. Жаль, что нет — как в Ехселе — чего-то типа «активной ячейки».

              Сообщение отредактировано: bi-lya — 22.06.07, 04:18

              Profi

              Old Bat



              Сообщ.
              #6

              ,
              22.06.07, 05:15

                Moderator

                *****

                Рейтинг (т): 128

                естественно, вариант с Information гораздо шустрее, я всего лишь показал еще одну альтернативную возможность, оговорившись, что это вариант на любителя ;)


                bi-lya



                Сообщ.
                #7

                ,
                25.06.07, 10:26

                  Senior Member

                  ****

                  Рейтинг (т): 34

                  Может, подскажете еще каким образом определить, какие Rectangle и Paragraph являются активными, т.е. в которых находится курсор?
                  Пока — для определения Rectangles — пользуюсь просто выяснением количества Rectangles, и в общем-то оно работает, потому что (то, что пока мне встретилось) при наличии колонтитулов Rectangles «текстового поля» оказывается в нумерации последним, но это, конечно, до поры

                  ExpandedWrap disabled

                    ActiveDocument.ActiveWindow.Panes(1).Pages(a).Rectangles.Count

                  А для определения активного параграфа попробовал по примеру Old Bat‘а с использованием объектной схемы — но… :wub:

                  Сообщение отредактировано: bi-lya — 25.06.07, 10:31


                  coder



                  Сообщ.
                  #8

                  ,
                  25.06.07, 11:26

                    Selection.Information (wdActiveEndPageNumber) — это активная страница.

                    Добавлено 25.06.07, 11:50
                    ActiveDocument.Range(1,selection.start).Paragraphs.Count — активный


                    XOXOJI



                    Сообщ.
                    #9

                    ,
                    30.03.09, 17:31

                      Junior

                      *

                      Рейтинг (т): 1

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

                      подскажите плиз

                      Profi

                      Old Bat



                      Сообщ.
                      #10

                      ,
                      31.03.09, 19:01

                        Moderator

                        *****

                        Рейтинг (т): 128

                        0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                        0 пользователей:

                        • Предыдущая тема
                        • VB for Application
                        • Следующая тема

                        Рейтинг@Mail.ru

                        [ Script execution time: 0,0838 ]   [ 16 queries used ]   [ Generated: 14.04.23, 17:33 GMT ]  

                        INTELLIGENT WORK FORUMS
                        FOR COMPUTER PROFESSIONALS

                        Contact US

                        Thanks. We have received your request and will respond promptly.

                        Log In

                        Come Join Us!

                        Are you a
                        Computer / IT professional?
                        Join Tek-Tips Forums!

                        • Talk With Other Members
                        • Be Notified Of Responses
                          To Your Posts
                        • Keyword Search
                        • One-Click Access To Your
                          Favorite Forums
                        • Automated Signatures
                          On Your Posts
                        • Best Of All, It’s Free!

                        *Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

                        Posting Guidelines

                        Promoting, selling, recruiting, coursework and thesis posting is forbidden.

                        Students Click Here

                        Setting cursor in word doc

                        Setting cursor in word doc

                        (OP)

                        2 Sep 04 10:42

                        How do I programatically (from VB application) set the cursor to be in a specific location when I open up a word doc?

                        Thanks,

                        Shannan

                        Red Flag Submitted

                        Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
                        The Tek-Tips staff will check this out and take appropriate action.

                        Join Tek-Tips® Today!

                        Join your peers on the Internet’s largest technical computer professional community.
                        It’s easy to join and it’s free.

                        Here’s Why Members Love Tek-Tips Forums:

                        • Tek-Tips ForumsTalk To Other Members
                        • Notification Of Responses To Questions
                        • Favorite Forums One Click Access
                        • Keyword Search Of All Posts, And More…

                        Register now while it’s still free!

                        Already a member? Close this window and log in.

                        Join Us             Close

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