Microsoft Office Forums

Go Back   Microsoft Office Forums > >

Reply
 
Thread Tools Display Modes
  #1  
Old 04-12-2020, 06:15 AM
jpl jpl is offline Selection object and its Range property Windows 7 64bit Selection object and its Range property Office 2010 32bit
Advanced Beginner
Selection object and its Range property
 
Join Date: Jan 2016
Location: France
Posts: 33
jpl is on a distinguished road
Question Selection object and its Range property

Bonjour
Peut être pourrez vous m'aider à comprendre le problème suivant.
Il s'agit de la relation entre les objets Selection et Range.

La macro suivante compare un objet Selection et l'objet Range de cette Selection.
Elle affiche les propriétés Start et End de ces deux objets, leur propriété Text et enfin le texte du premier
élément de leur collection Characters, converti en code Asci.



Si la macro est lancée sur une sélection non vide, les résultats sont conformes à ce que l'on peut espérer.

Mais si je lance cette macro sur une sélection réduite à un point d'insertion, je ne comprends pas pourquoi :
1 la propriété Text de l'objet Range renvoie la chaine vide, alors que la propriété Text de l'objet Selection
renvoie le premier caractère qui suit le point d'insertion.
2 alors que les objets Selection et Range sont vides, leur collection Characters ne l'est pas et contient
le premier "objet" Character qui les suit ?

Pour quelle raison la propriété Text de ces deux objets est-elle différente, et pourquoi la collection
Characters n'est elle pas vide ?

Hello
Maybe you can help me understand the following problem.
This is the relationship between the Selection and Range objects.

The following macro compares a Selection object and the Range object of this Selection.
It displays the Start and End properties of these two objects, their Text property and finally the text of
the first element of their Characters collection, converted into Asci code.

If the macro is launched on a non-empty selection, the results are as expected.
But if I run this macro on a selection reduced to an insertion point, I don't understand why:
1 the Text property of the Range object returns the empty string, while the Text property of the
Selection object returns the first character after the insertion point.
2 while the Selection and Range objects are empty, their Characters collection is not and contains
the first Character "object" which follows them?

Why is the Text property of these two objects different, and why is the Characters collection not empty?
Code:
Sub ComparaisonSelectionRangeVides()
  Dim plage As Range
  Dim DébutSel As Long, FinSel As Long
  With Selection
    DébutSel = .Start: FinSel = .End
    Debug.Print "Étendue de la sélection : " & DébutSel & "->" & FinSel
    Debug.Print "Texte de la sélection : """ & .Text & """"
    Debug.Print "Premier Caractère de la sélection : " & CharacterEnAsci(.Characters(1))
  End With
  Debug.Print

'  Set plage = ActiveDocument.Range(Start:=DébutSel, End:=FinSel)
   Set plage = Selection.Range
 With plage
    Debug.Print "Étendue de la plage : " & .Start & "->" & .End
    Debug.Print "Texte de la plage : """ & .Text & """"
    Debug.Print "Premier Caractère de la plage : " & CharacterEnAsci(.Characters(1))
  End With
  Debug.Print

End Sub

Function CharacterEnAsci(Ch As Range) As String
  Dim s As String, i As Long, stemp As String
  s = Ch.Text
  For i = 1 To Len(s)
    stemp = stemp & "ch(" & Asc(Mid(s, i, 1)) & ") "
  Next i
  CharacterEnAsci = stemp
End Function
Reply With Quote
  #2  
Old 04-12-2020, 03:21 PM
macropod's Avatar
macropod macropod is offline Selection object and its Range property Windows 7 64bit Selection object and its Range property Office 2010 32bit
Administrator
 
Join Date: Dec 2010
Location: Canberra, Australia
Posts: 21,956
macropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond repute
Default

You can resolve the inconsistency between 'Texte de la sélection' and 'Texte de la plage' by changing:
With Selection
to:
With Selection.Range

The inconsistency between the 'Texte de la sélection' and 'Texte de la plage' on the one hand and the 'Premier Caractère de la sélection' and 'Premier Caractère de la plage' on the other are just a quirk of how VBA works. You can resolve those issues by testing the selection type (or by subtracting the range end from its start) and, if Selection.Type < 2, or the range length is 0, not reporting CharacterEnAsci(.Characters(1)).
__________________
Cheers,
Paul Edstein
[Fmr MS MVP - Word]
Reply With Quote
  #3  
Old 04-13-2020, 03:06 AM
jpl jpl is offline Selection object and its Range property Windows 7 64bit Selection object and its Range property Office 2010 32bit
Advanced Beginner
Selection object and its Range property
 
Join Date: Jan 2016
Location: France
Posts: 33
jpl is on a distinguished road
Default

Merci pour votre réponse.
Je me demandais si ces comportements avaient une justification profonde qui m'échappait, vous me rassurez en les qualifiant de bizarreries.

Autre sujet de perplexité, il s'agit cette fois de la relation entre les objets Selection et Range à l'intérieur d'un tableau Word (objet Table).

Mon document contient un tableau de deux lignes et cinq colonnes.

L'idée est de sélectionner une colonne de tableau, et de comparer les objet Selection et Range qui correspondent à cette colonne.

La macro principale est divisée en cinq sections.
Elle dresse la liste des cellules des objets Selection et Range et affiche leurs "coordonnées" dans la fenêtre immédiate. Elle est testée dans la macro Test.

Si je sélectionne la deuxième colonne, la section 1 me dit que l'objet Selection contient deux cellules (objets Cells), ce qui est tout à fait normal. Leur coordonnées confirment que ce sont bien les cellules de la colonne 2.
La section 2 définit l'objet Plage comme Range de la sélection.
Les sections 3 et 4 parcourent la collection Plage.Cells et indiquent que l'objet Plage s'étend de la première à la dernière cellule de la colonne, y compris toutes les cellules intermédiaires en lisant de gauche à droite et de haut en bas.
Ceci me semble cohérent puisqu'un Range est une zone contiguë dans un document.
La section 5 sélectionne l'objet Plage.
Premier problème : l'objet Plage contient six cellules, mais quand on le sélectionne, la sélection n'en contient que deux au lieu des six que l'on pourrait espérer. Lorsqu'on sélectionne un Range dans un objet Table, il semblerait que la sélection ne soit pas la zone du Range, mais une zone rectangulaire s'appuyant sur les cellules extrêmes du Range.

Si je sélectionne la première colonne, l'objet Selection contient deux cellules, l'objet Plage en contient six, ce qui est conforme au résultat précédent.
Deuxième problème : les sections 3 et 4 indiquent que l'objet Plage contient 6 cellules, mais elles n'en trouvent que 5 à afficher. La section 4 provoque un message d'erreur indiquant que la cellule Plage.Cells(6) n'existe pas. Qu'est devenue ma cellule fantôme ?

Excusez moi pour la longueur du message, ce ne sont pas des sujets très importants, mais cela m'occupe pendant le confinement.

Thank you for your reply.
I was wondering if these behaviors had a deep justification that escaped me, you reassure me by calling them quirks.

Another subject of perplexity, it is this time about the relation between the Selection and Range objects inside a Word table (Table object).

My document contains a table of two rows and five columns.

The idea is to select a column, and compare the Selection and Range objects that correspond to this column.

The main macro is divided into five sections.
It lists the cells of the Selection and Range objects and displays their "coordinates" in the immediate window. It is tested in the Test macro.


If I select the second column, section 1 tells me that the Selection object contains two cells (Cells objects), which is completely normal. Their coordinates confirm that these are the cells in column 2.
Section 2 defines the Plage object as the Selection range.
Sections 3 and 4 run through the Plage.Cells collection and indicate that the Plage object extends from the first to the last cell of the column, including all the intermediate cells by reading from left to right and from top to bottom.
This seems coherent to me since a Range is a contiguous zone in a document.
Section 5 selects the Plage object.
First problem: the Range object contains six cells, but when it is selected, the selection contains only two instead of the six that one might hope for. When you select a Range in a Table object, it would seem that the selection is not the Range area, but a rectangular area based on the extreme cells of the Range.

If I select the first column, the Selection object contains two cells, the Plage object contains six, which is consistent with the previous result.
Second problem: Sections 3 and 4 indicate that the Plage object contains 6 cells, but they only find 5 cells to display. Section 4 generates an error message indicating that the Plage.Cells (6) cell does not exist. What happened to my ghost cell?


Excuse me for the length of the message, these are not very important subjects, but that occupies me during the confinement.


Code:
Sub ComparaisonSelectionRange(NumeroColonne As Integer)
    Dim Plage As Range, Cellule As Cell
    Dim I As Integer, J As Integer
    Debug.Print "Colonne n° " & NumeroColonne
    On Error GoTo SiErreur
    ActiveDocument.Tables(1).Columns(NumeroColonne).Select
    
    1 'On affiche le nombre de cellules de la sélection
      'et leurs coordonnées
    With Selection
      Debug.Print " 1 Sélection"
      Debug.Print "     Nombre de cellules : " & .Cells.Count
      Debug.Print "     Coordonnées des cellules de la sélection : "
      For Each Cellule In .Cells
        CoordonnéesCellule Cellule, I, J
        Debug.Print "      (" & I & "," & J & ")"
      Next
      Debug.Print
    End With
    
    2 'On définit le range de la sélection, et on le sélectionne
    Set Plage = Selection.Range
    Debug.Print " 2 L'objet Plage est défini"
    Debug.Print
    
    3 'On parcourt la collection Plage.Cells
    With Plage
      Debug.Print " 3 Plage"
      Debug.Print "     Nombre de cellules : " & .Cells.Count
      Debug.Print "     Coordonnées des cellules de la plage : "
      For Each Cellule In .Cells
        CoordonnéesCellule Cellule, I, J
        Debug.Print "      (" & I & "," & J & ")"
      Next
      Debug.Print
    End With
    
    4 'On parcourt la collection Plages.Cells par item
    Dim K As Integer
    With Plage
      Debug.Print " 4 Plage"
      Debug.Print "    Nombre de cellules : " & .Cells.Count
      Debug.Print "    Coordonnées des cellules de la plage : "
      For K = 1 To .Cells.Count
        CoordonnéesCellule .Cells.Item(K), I, J
        Debug.Print "      (" & I & "," & J & ")"
      Next K
    End With
    
    5 'On sélectionne l'objet Plage
    Debug.Print
    Plage.Select
    Debug.Print " 5 Plage sélectionnée"
    Debug.Print "     Nombre de cellules de la plage : " & Plage.Cells.Count
    Debug.Print "     Nombre de cellules de la sélection : " & Selection.Cells.Count
    Debug.Print
    
    Set Plage = Nothing
    Set Cellule = Nothing
    Exit Sub
    
    SiErreur:
    MsgBox "K = " & K & ". " & Err.Description
    Resume 5
    
  End Sub
   
   
   
  Sub CoordonnéesCellule(Cellule As Cell, I As Integer, J As Integer)
    'inspirée de macropod
    I = Cellule.RowIndex
    J = Cellule.ColumnIndex
  End Sub
   
   Sub Test()
    'Mettre un point d'arrêt sur la dernière instruction

     ComparaisonSelectionRange 2
     ComparaisonSelectionRange 1
   End Sub
Reply With Quote
  #4  
Old 04-13-2020, 05:43 AM
macropod's Avatar
macropod macropod is offline Selection object and its Range property Windows 7 64bit Selection object and its Range property Office 2010 32bit
Administrator
 
Join Date: Dec 2010
Location: Canberra, Australia
Posts: 21,956
macropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond reputemacropod has a reputation beyond repute
Default

Quote:
Originally Posted by jpl View Post
Another subject of perplexity, it is this time about the relation between the Selection and Range objects inside a Word table (Table object).

...
First problem: the Range object contains six cells, but when it is selected, the selection contains only two instead of the six that one might hope for. When you select a Range in a Table object, it would seem that the selection is not the Range area, but a rectangular area based on the extreme cells of the Range.

If I select the first column, the Selection object contains two cells, the Plage object contains six, which is consistent with the previous result.
[I]Second problem: Sections 3 and 4 indicate that the Plage object contains 6 cells, but they only find 5 cells to display. Section 4 generates an error message indicating that the Plage.Cells (6) cell does not exist. What happened to my ghost cell?[/I
When you define a range within a table, the range goes horizontally from the first designated cell to the end of the row before going to the next row, starting at the first cell in that row, and so on, until the last designated cell is reached. This is quite unlike how a Selection works. As for the 'ghost' cell, you have encountered a Word VBA bug.
__________________
Cheers,
Paul Edstein
[Fmr MS MVP - Word]
Reply With Quote
  #5  
Old 04-13-2020, 06:05 AM
jpl jpl is offline Selection object and its Range property Windows 7 64bit Selection object and its Range property Office 2010 32bit
Advanced Beginner
Selection object and its Range property
 
Join Date: Jan 2016
Location: France
Posts: 33
jpl is on a distinguished road
Default

Merci pour ces informations.
Reply With Quote
Reply

Thread Tools
Display Modes


Similar Threads
Thread Thread Starter Forum Replies Last Post
Distribute text in one cell across a range of cells (overcoming selection.range.cells.count bug) slaycock Word VBA 0 02-18-2017 07:00 AM
Selection object and its Range property Working with Selection.range. PRA007 Word VBA 2 02-19-2016 12:52 AM
Selection or Range Tommes93 Word VBA 1 04-10-2014 02:50 AM
Selection object and its Range property Use of Range Object Question jsb73 Word VBA 6 08-14-2012 07:35 PM
Cannot access most of property of MailItem object on Windows Server 2008 64 bit tz900 Outlook 0 04-10-2012 12:55 PM

Other Forums: Access Forums

All times are GMT -7. The time now is 02:20 PM.


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2024, vBulletin Solutions Inc.
Search Engine Optimisation provided by DragonByte SEO (Lite) - vBulletin Mods & Addons Copyright © 2024 DragonByte Technologies Ltd.
MSOfficeForums.com is not affiliated with Microsoft