Позиция курсора word vba

  • 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.

I have a Word table in which I want to hide or reveal text in specific columns. I have written a macro linked to a check box in the header row. Ticking the box is supposed to hide the text in a column on the row where the cursor sits. The macro works fine when I test the VBA, but when I run it using the tick box, the code «thinks» the relevant row is the header row where the tick box resides.

How can I relay the correct row index (i.e. the row selected, where the text cursor sits, before the tick box is ticked) to the macro?

Maybe the correct question is: How does one differentiate between the cursor position in text (in a Word table) and the mouse cursor position?

Here is the macro code…

Private Sub CheckBox1_Click()
Call HideOrRevealAnswer
End Sub

Sub HideOrRevealAnswer()

Dim iCellRange As Range
Dim iColStart, iColEnd As Integer
Dim iRow As Integer

iColStart = 4 'column for Answers
iColEnd = 5 'column for Explanation

With ActiveDocument
    iRow = Selection.Cells(1).RowIndex
    Set iCellRange = .Range(Start:=.Tables(1).Cell(iRow,iColStart).Range.Start, _
        End:=.Tables(1).Cell(iRow, iColEnd).Range.End)
    iCellRange.Select
End With

With iCellRange
    Select Case .Font.Color
        Case wdColorAutomatic
            .Font.Color = wdColorWhite
        Case wdColorWhite
            .Font.Color = wdColorAutomatic
    End Select
End With

End Sub

maksim_volodin

3 / 2 / 1

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

Сообщений: 33

1

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

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


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

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

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

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



0



Alex77755

11482 / 3773 / 677

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

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

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,147

02.05.2019, 13:17

4

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

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



1



Модератор

Эксперт MS Access

11343 / 4661 / 749

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

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

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

02.05.2019, 13:23

5

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

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

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



0



11482 / 3773 / 677

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

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

02.05.2019, 16:43

6

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



0



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

Finding current cursor position in MS Word. Coding in Visual Basic

Finding current cursor position in MS Word. Coding in Visual Basic

(OP)

21 Mar 02 03:30

I am currently programming using the Visual Basic Editor in MS Word. I recorded several macros so just so I can insert the SEQ numbering on a paragraph.

However, I need to know how I can find the returned value of the current cursor position because I search for the section mark first and I want the cursor to return to the line that I first clicked on before inserting the SEQ num.

Is this possible? Please help me. I need this badly.

Thank you very much!

ConsVbGem28

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

Like this post? Please share to your friends:
  • Позиционные аргументы функций в word
  • Позиции табуляции для word
  • Позиции табуляции выставляются в ms word
  • Позиции табуляции в ms word допускают выравнивание
  • Поздравления для microsoft word