本周早些时候我发布了一个有关 HTML 到 Excel 转换的问题,该问题对我来说效果很好。我得到的示例宏代码很好地将代码从 HTML 格式转换为 Excel 单元格(感谢 Siddharth Rout!)。我现在遇到的问题似乎无法在任何地方找到答案,这与 IE 对象如何处理 Excel 中的段落、分隔符和列表项有关。 p、br 和 li 将文本移动到原始单元格下方的单元格中,覆盖这些单元格中的所有数据。有没有办法让 HTML block 仅显示在一个单元格中(意味着每个新行标记只会在同一单元格中创建一个新行)?
VBA代码
Sub Sample()
Dim Ie As Object
Set Ie = CreateObject("InternetExplorer.Application")
With Ie
.Visible = False
.Navigate "about:blank"
.document.body.InnerHTML = Sheets("Sheet1").Range("A1").Value
.document.body.createtextrange.execCommand "Copy"
ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("A1")
.Quit
End With
End Sub
示例 HTML
<p> Here are some possible uses:</p> <ul> <li><font color = "red"> syntax highlighting code snippets</font></li> <li style ="font-weight:bold; color: orange">validating credit card numbers, phone numbers, and zip codes</li> <li style = "font-style: italic">styling email addresses and tags</li> </ul>
示例输出在多行上显示(希望在一个单元格中的多行上显示 - 类似于 Shift+Enter 的工作方式)
Here are some possible uses:
syntax highlighting code snippets
**validating credit card numbers, phone numbers, and zip codes**
*styling email addresses and tags*
最佳答案
我不确定你是否可以做到这一点(我可能是错的)。但如果这只是您的数据被覆盖的问题,那么这里有一个替代方案:)
逻辑:不要将其粘贴到同一张工作表中,而是将其粘贴到临时工作表中,然后复制这些行并将其插入到工作表 1 中,这样数据就不会出现在工作表中。被覆盖。查看快照。
快照:
代码:
Sub Sample()
Dim ws As Worksheet, wstemp As Worksheet
Dim Ie As Object
Dim LastRow As Long
Set Ie = CreateObject("InternetExplorer.Application")
Set ws = Sheets("Sheet1")
'~~> Create Temp Sheet
Set wstemp = Sheets.Add
With Ie
.Visible = True
.Navigate "about:blank"
'~~> I am assuming that the data is in Cell A1
.document.body.InnerHTML = ws.Range("A1").Value
'~~> Deleting the row which had the html string. I am assuming that it was in Row 1
ws.Rows(1).Delete
.document.body.createtextrange.execCommand "Copy"
wstemp.Paste Destination:=wstemp.Range("A1")
'~~> Find the last row in the temp sheet
LastRow = wstemp.Cells.Find(What:="*", After:=wstemp.Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
'~~> Copy that data
wstemp.Rows("1:" & LastRow).Copy
'~~> insert it in Sheet1
ws.Rows(1).Insert Shift:=xlDown
.Quit
End With
'~~> Delete Temp sheet
Application.DisplayAlerts = False
wstemp.Delete
Application.DisplayAlerts = True
End Sub
HTH
关于vba - HTML 到 Excel 格式转换 - Break 和 li 在同一单元格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10035914/