View Single Post
 
Old 10-29-2022, 06:11 AM
BrianHoard BrianHoard is offline Windows 10 Office 2019
Advanced Beginner
 
Join Date: Jul 2022
Location: Haymarket, VA USA
Posts: 85
BrianHoard is on a distinguished road
Default

If you're looking for the character/range position in the document, this might help. If you're looking for the X,Y position on the screen, that's a different problem.
Italophile's solutions may work better, as mine would of course change if you changed the document, moving things around. But this stores the current position of your text as the Range.Start attribute.

What exactly are you trying to do with this position once you store it? Just curious as I have never needed to know the position of something in a document. I have needed to know positions when building a UI, or dealing with images, etc. Understanding more of what your bigger goal is may help us help you get there.

Code:
Sub position()
  ' Find characters 1150 and store position in a variable.
  
  Dim docRange As Range
  Set docRange = ActiveDocument.Range
  Dim str_text As String
  str_text = "1150"
  Dim position As Long
  Dim str_message As String
  
  With docRange.Find
    .ClearFormatting
    .Text = str_text
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
  End With
  
  docRange.Find.Execute
  ' Store range
  position = docRange.Start
  ' Define message for msgBox
  str_message = (str_text & " is at position: " & position & ".")
  
  Call MsgBox(prompt:=str_message, Buttons:=vbOKOnly)
  
End Sub
Attached Images
File Type: png positionSnap.png (7.6 KB, 17 views)
Reply With Quote