Vba word cell text

It took me a long while to figure out how to do this, as it was my first time programming in Visual Basic and VBA, but this is how i solved it:

The first problem i had was that i had some junk characters i had to get rid of, which i tried using

WorksheetFunction.Clean(MyString)

Problem is this deletes non printing characters which are imported (ASCII code 0-31) which included ascii code 13 (line jump or carriage return).

Even without using WorksheetFunction.clean line jump was not correctly interpreted by excel, which i solved using this

Dim str as String
Dim clearer As String
str=.cell(iRow, iCol).Range.Text 'Get non treated content from word table cell
clearer = Replace(str, Chr(13), vbNewLine)

Now that i was not cleaning automatically all stuff, i had to do it manually, but i did not know the Ascii code of strange characters.

I looked for them this way

 Dim Counter As Integer
MsgBox ("Word " + str)
For Counter = 1 To Len(str)
MsgBox ("Letter is " + Mid(str, Counter, 1) + "And Ascii code is" + 
 CStr(AscW(Mid(str, Counter, 1))))
Next

Once I knew their code, the process for manual cleaning was the same for other characters. Some of them represented a line_jump and some others were junk, so i treated them in a different way

clearer = Replace(str, Chr(13), vbNewLine) 'Replace line jumps from word to excel
clearer = Replace(clearer, Chr(11), vbNewLine) 'Replace line jumps from word 
to excel
clearer = Replace(clearer, Chr(7), "") 'Remover char

This way, i could clean the imported text as i wanted. Hope this can help someone in the future.

  • Remove From My Forums
  • Question

  • Hi,

    I need to read a line in ms word table cell. There are 3 line in a cell and I’d like to read line by line and put a line in a  string variable. Would anyone be willing to help me here? I’m so desperate with the answer since I tried everything and none are working.

    What I did so far:
    If (Mid(theTable.Cell(caseStartRow, 2).Range.Text, 1, _
                                                Len(theTable.Cell(caseStartRow, 2).Range.Text) — 2)) = chrs$(13) Then

                                                           objFile.WriteLine («»)
                        objFile.WriteLine («»)
     End If

    Please help. Thanks so much!!

title ms.prod ms.assetid ms.date

Working with Tables

word

cf0858b7-6b39-4c90-552e-edb695b5cda3

06/08/2017

Working with Tables

This topic includes Visual Basic examples related to the following tasks:

  • Creating a table, inserting text, and applying formatting

  • Inserting text into a table cell

  • Returning text from a table cell without returning the end of cell marker

  • Converting text to a table

  • Returning the contents of each table cell

  • Copying all tables in the active document into a new document

Creating a table, inserting text, and applying formatting

The following example inserts a four-column, three-row table at the beginning of the active document. The For Each…Next structure is used to step through each cell in the table. Within the For Each…Next structure, the InsertAfter method of the Range object is used to add text to the table cells (Cell 1, Cell 2, and so on).

Sub CreateNewTable() 
 Dim docActive As Document 
 Dim tblNew As Table 
 Dim celTable As Cell 
 Dim intCount As Integer 
 
 Set docActive = ActiveDocument 
 Set tblNew = docActive.Tables.Add( _ 
 Range:=docActive.Range(Start:=0, End:=0), NumRows:=3, _ 
 NumColumns:=4) 
 intCount = 1 
 
 For Each celTable In tblNew.Range.Cells 
 celTable.Range.InsertAfter "Cell " &; intCount 
 intCount = intCount + 1 
 Next celTable 
 
 tblNew.AutoFormat Format:=wdTableFormatColorful2, _ 
 ApplyBorders:=True, ApplyFont:=True, ApplyColor:=True 
End Sub

Inserting text into a table cell

The following example inserts text into the first cell of the first table in the active document. The Cell method returns a single Cell object. The Rangeproperty returns a Range object. The Delete method is used to delete the existing text and the InsertAftermethod inserts the «Cell 1,1» text.

Sub InsertTextInCell() 
 If ActiveDocument.Tables.Count >= 1 Then 
 With ActiveDocument.Tables(1).Cell(Row:=1, Column:=1).Range 
 .Delete 
 .InsertAfter Text:="Cell 1,1" 
 End With 
 End If 
End Sub

Returning text from a table cell without returning the end of cell marker

The following example returns and displays the contents of each cell in the first row of the first document table.

Sub ReturnTableText() 
 Dim tblOne As Table 
 Dim celTable As Cell 
 Dim rngTable As Range 
 
 Set tblOne = ActiveDocument.Tables(1) 
 For Each celTable In tblOne.Rows(1).Cells 
 Set rngTable = ActiveDocument.Range(Start:=celTable.Range.Start, _ 
 End:=celTable.Range.End - 1) 
 MsgBox rngTable.Text 
 Next celTable 
End Sub
Sub ReturnCellText() 
 Dim tblOne As Table 
 Dim celTable As Cell 
 Dim rngTable As Range 
 
 Set tblOne = ActiveDocument.Tables(1) 
 For Each celTable In tblOne.Rows(1).Cells 
 Set rngTable = celTable.Range 
 rngTable.MoveEnd Unit:=wdCharacter, Count:=-1 
 MsgBox rngTable.Text 
 Next celTable 
End Sub

Converting existing text to a table

The following example inserts tab-delimited text at the beginning of the active document and then converts the text to a table.

Sub ConvertExistingText() 
 With Documents.Add.Content 
 .InsertBefore "one" &; vbTab &; "two" &; vbTab &; "three" &; vbCr 
 .ConvertToTable Separator:=Chr(9), NumRows:=1, NumColumns:=3 
 End With 
End Sub

Returning the contents of each table cell

The following example defines an array equal to the number of cells in the first document table (assuming Option Base 1). The For Each…Next structure is used to return the contents of each table cell and assign the text to the corresponding array element.

Sub ReturnCellContentsToArray() 
 Dim intCells As Integer 
 Dim celTable As Cell 
 Dim strCells() As String 
 Dim intCount As Integer 
 Dim rngText As Range 
 
 If ActiveDocument.Tables.Count >= 1 Then 
 With ActiveDocument.Tables(1).Range 
 intCells = .Cells.Count 
 ReDim strCells(intCells) 
 intCount = 1 
 For Each celTable In .Cells 
 Set rngText = celTable.Range 
 rngText.MoveEnd Unit:=wdCharacter, Count:=-1 
 strCells(intCount) = rngText 
 intCount = intCount + 1 
 Next celTable 
 End With 
 End If 
End Sub

Copying all tables in the active document into a new document

This example copies the tables from the current document into a new document.

Sub CopyTablesToNewDoc() 
 Dim docOld As Document 
 Dim rngDoc As Range 
 Dim tblDoc As Table 
 
 If ActiveDocument.Tables.Count >= 1 Then 
 Set docOld = ActiveDocument 
 Set rngDoc = Documents.Add.Range(Start:=0, End:=0) 
 For Each tblDoc In docOld.Tables 
 tblDoc.Range.Copy 
 With rngDoc 
 .Paste 
 .Collapse Direction:=wdCollapseEnd 
 .InsertParagraphAfter 
 .Collapse Direction:=wdCollapseEnd 
 End With 
 Next 
 End If 
End Sub

Автор blacktesta, 04 ноября 2019, 20:19

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

Саму ячейку можно выделить таким кодом (выделяется первая ячейка в первой таблице):
ActiveDocument.Tables(1).Cell(1, 1).Select

А как выделить весь текст в ячейке при помощи VBA?



Администратор

  • Administrator
  • Сообщения: 2,252
  • Записан

Выделение текста ячейки:

Макрос

Sub Макрос1()

        Dim tbl As Table

            ‘ Присваиваем первой таблице имя «tbl», чтобы было удобно читать и писать код.
    Set tbl = ActiveDocument.Tables(1)
    ‘ Выделение первой ячейки в таблице.
    tbl.Cell(1, 1).Select
    ‘ Убираем с конца символ-кружок.
    Selection.MoveEnd Unit:=wdCharacter, Count:=-1

        ‘ Здесь у нас выделен весь текст ячейки.
        ‘ Например, можно посмотреть текст ячейки.
        ‘ Если ячейка пустая, то вернётся символ-кружок, а не пустая строка.
        ‘ Вывод текста в View — Immediate Window.
    Debug.Print Selection.Text

    End Sub

[свернуть]

Не всегда есть необходимость выделять (использование Selection), а достаточно использовать Range:

Макрос

Sub Макрос2()

       Dim tbl As Table, rng As Range

          ‘ Присваиваем первой таблице имя «tbl», чтобы было удобно читать и писать код.
    Set tbl = ActiveDocument.Tables(1)
    ‘ Присваиваем имя «rng» содержимому ячейки.
    Set rng = tbl.Cell(1, 1).Range.Duplicate
    ‘ Убираем с конца символ-кружок.
    rng.MoveEnd Unit:=wdCharacter, Count:=-1

        ‘ Здесь «rng» — это весь текст ячейки.
        ‘ Например, можно посмотреть текст ячейки.
        ‘ Если ячейка пустая, то вернётся пустая строка.
        ‘ Вывод текста в View — Immediate Window.
    Debug.Print rng.Text

    End Sub

[свернуть]


Огромное спасибо!!! Все работает. По видимому загвоздка была в этом символе-кружке.


  • Форум по VBA, Excel и Word

  • Word

  • Макросы в Word

  • Word VBA Макросы: Как обратиться/выделить текст в ячейке в таблице в ворде?

Multiple objectsCells
Cell
Multiple objects

Represents a single table cell. The Cell object is a member of the Cells
collection. The Cells collection represents all the cells in the specified object.

Using the Cell Object

Use Cell(row, column), where row is the row number and column is the column number, or Cells(index), where index is the index number, to return a Cell object. The following example applies shading to the second cell in the first row.

Set myCell = ActiveDocument.Tables(1).Cell(Row:=1, Column:=2)
myCell.Shading.Texture = wdTexture20Percent
		

The following example applies shading to the first cell in the first row.

ActiveDocument.Tables(1).Rows(1).Cells(1).Shading _
    .Texture = wdTexture20Percent
		

Use the Add
method to add a Cell object to the Cells collection. You can also use the InsertCells
method of the Selection object to insert new cells. The following example adds a cell before the first cell in myTable.

Set myTable = ActiveDocument.Tables(1)
myTable.Range.Cells.Add BeforeCell:=myTable.Cell(1, 1)
		

The following example sets a range (myRange) that references the first two cells in the first table. After the range is set, the cells are combined by the Merge method.

Set myTable = ActiveDocument.Tables(1)
Set myRange = ActiveDocument.Range(myTable.Cell(1, 1) _
    .Range.Start, myTable.Cell(1, 2).Range.End)
myRange.Cells.Merge
		

Remarks

Use the Add method with the Rows or Columns collection to add a row or column of cells.

Use the Information
property with a Selection object to return the current row and column number. The following example changes the width of the first cell in the selection and then displays the cell’s row number and column number.

If Selection.Information(wdWithInTable) = True Then
    With Selection
        .Cells(1).Width = 22
        MsgBox "Cell " & .Information(wdStartOfRangeRowNumber) _
            & "," & .Information(wdStartOfRangeColumnNumber)
    End With
End If
		

Понравилась статья? Поделить с друзьями:
  • Vba word application commandbars
  • Vba word activedocument words
  • Vba word activedocument close
  • Vba with word 2010
  • Vba with word 2007