问题
I have a table in a Word file. This vba program below will iterate through all the table cells
Dim strCellText As String
Dim uResp As String
Dim Row As Integer
Dim Col As Integer
Dim itable As Table
For Each itable In ThisDocument.Tables
uResp = ""
For Row = 1 To itable.Rows.Count
For Col = 1 To itable.Columns.Count
strCellText = itable.Cell(Row, Col).Range.Text
uResp = uResp & Trim(strCellText)
Next
Next
MsgBox uResp
Next
In the line uResp = uResp & Trim(strCellText)
VBA appends a newline and a dot to each cell.So MsgBox uResp
will display a 'column' message box.How can I remove the newline and dot while displaying the message box.
回答1:
Word uses two characters as the cell delimiter, so use
uResp = uResp & Trim(left(strCellText,len(StrCellText)-2))
In this case, you will have no separator between the cell values, so you might want to concatenate a space.
回答2:
Try adding the Replace function and InstrRev to find the last newline and . in the celltext, then Left the celltext and store the Cleaned result
strCellText = itable.Cell(Row, Col).Range.Text
'added
Clean = Trim(strcelltext)
posFromEnd = InStrRev(Clean, vbCr + chr(7)) 'obviously a newline and a chr(7) ..
If (posFromEnd > 0) Then
Clean = Trim(Left(Clean, posFromEnd - 1))
End If
'end added
uResp = uResp & Clean 'updated
To verify what the last chars are in the string do this in the debugger:
strCellText = itable.Cell(Row, Col).Range.Text
For r = 1 To Len(strCellText)
c = Mid(strCellText, r, 1)
Debug.Print Right("0" + Hex(Asc(c)), 2) + " ";
Next
Debug.Print 'set a breakpoint here
From the immediate window copy the result so we can reason from there
回答3:
If you are sure this will ALWAYS happen you could just shorten the string by two characters:
MsgBox LEFT(uResp,LEN(uResp)-2)
EDIT: Of course, vinod is correct. Not uResp has to be shortend, but strCellText. But this answer has already been given. Sorry for the mistake.
回答4:
The solution I use is:
endOfCell = Chr(13) + Chr(7)
uResp = uResp & Split(strCellText, endOfCell)(0)
来源:https://stackoverflow.com/questions/15585202/how-to-trim-table-cell-values-in-ms-word-with-vba