Для начала убедитесь, что опция «Перенос текста» включена для ячейки, в которую вы пишете, иначе разрывы строк не будут отображаться должным образом, даже если они существуют в тексте.
Now that this is cleared out of the way, there are 2 different reasons why your code doesn't preserve the line breaks from the Word table. The first is that you are using the CLEAN function. The second is that there's a problem with how data is passed from the Word table using VBA (some information is lost). Luckily, there are ways to solve those problems.
Avoid using the CLEAN function
When you use the CLEAN function, you remove all the non-printable characters from a string of text. The problem is that the "formatting" that you see in the Word table is actually caused by the presence of 2 non-printable characters (or at least one of them). Those characters are the carriage return (CR) and the line feed (LF) characters. By using the CLEAN function you are asking to remove those characters which removes the information indicating a line break.
So I tried to do the same as you without the CLEAN function and made a Word table
then I used the following code to write the content of the first cell to Excel.
Sub ReadFromWordTable()
Dim WordApp As Word.Application
Set WordApp = GetObject(, "Word.Application")
Dim WordDoc As Word.Document
Set WordDoc = WordApp.ActiveDocument
Dim xlSht As Worksheet
Set xlSht = ActiveSheet
Dim TempString As String
With WordDoc.Tables(1)
TempString = .Range.Text
End With
xlSht.Cells(1, 1).Value2 = TempString
'StringDrillDown TempString
End Sub
and saw that the line break does not appear (we'll come back to this later) and that there is some garbage characters at the end of my cell.
Now I see why you used the CLEAN function : to make those garbage characters go away! If only there was an out-of-the-box VBA function to remove those non-printable characters without removing CR and LF from the string!
Since there isn't any and that they only appear at the end, I would suggest to simply clean TempString
using the following code which will remove all the non-printable characters starting from the right and stop as soon as it encounters a printable character.
Dim i As Long, NbOfCharacter As Long
NbOfCharacter = Len(TempString)
For i = Len(TempString) To 1 Step -1
If Asc(Mid(TempString, i, 1)) < 32 Then
NbOfCharacter = NbOfCharacter - 1
Else
Exit For
End If
Next
TempString = Left(TempString, NbOfCharacter)
Note here that I'm using the As c функция . Он возвращает код символа Extended ASCII (также известный как ANSI) (число от 1 до 255), который однозначно идентифицирует символ. В нашем случае все непечатаемые символы возвращают значение ниже 32, поэтому мы можем легко их отфильтровать.
Убедитесь, что символ перевода строки присутствует в строке, которую вы пишете в ячейку
Как вы видели, когда мы использовали значение .Range.Text
напрямую, разрыв строки проходил неправильно. Чтобы понять проблему, мы могли бы захотеть детализировать различные символы, составляющие нашу переменную TempString. Для этого вы можете использовать такую процедуру:
Sub StringDrillDown(str As String)
Dim ws As Worksheet
With ActiveWorkbook
Set ws = .Sheets.Add(AFTER:=.Sheets(.Sheets.Count))
End With
ws.Range("A1") = "Character"
ws.Range("B1") = "Ascii Code"
Dim i As Long
For i = 1 To Len(str)
ws.Cells(i + 1, 1).Value2 = Mid$(str, i, 1)
ws.Cells(i + 1, 2).Value2 = Asc(Mid$(str, i, 1))
Next i
End Sub
Давая нам это:
введите описание изображения здесь
Что мы замечаем, так это то, что единственный символ, который у нас есть между «и» и «некоторые», - это символ номер 13, который соответствует CR (это похоже на причуду того, как строковые данные передаются между Word и Excel). Итак, нам не хватает LF, необходимого, чтобы дать понять Excel, что нам нужен разрыв строки между этими двумя словами.
Чтобы решить эту проблему, мы могли бы использовать следующее:
With WordDoc.Tables(1)
TempString = Replace(.Cell(1, 1).Range.Text, Chr(13), Chr(13) & Chr(10))
End With
Этот код заменяет все одинокие CR на CRLF (обратите внимание, что код символа для LF равен 10).
Предупреждение: если бы в строке уже были символы CRLF, строка кода выше удвоилась бы их, но здесь это не так.
Наконец, наш исходный пример кода теперь будет следующим:
Sub ReadFromWordTable()
Dim WordApp As Word.Application
Set WordApp = GetObject(, "Word.Application")
Dim WordDoc As Word.Document
Set WordDoc = WordApp.ActiveDocument
Dim xlSht As Worksheet
Set xlSht = ActiveSheet
Dim TempString As String
With WordDoc.Tables(1)
TempString = Replace(.Cell(1, 1).Range.Text, Chr(13), Chr(13) & Chr(10))
End With
Dim i As Long, NbOfCharacter As Long
NbOfCharacter = Len(TempString)
For i = Len(TempString) To 1 Step -1
If Asc(Mid(TempString, i, 1)) < 32 Then
NbOfCharacter = NbOfCharacter - 1
Else
Exit For
End If
Next
TempString = Left(TempString, NbOfCharacter)
xlSht.Cells(1, 1).Value2 = TempString
'StringDrillDown TempString
End Sub