excel - VBA - 将多行 HTML 粘贴到单个单元格中
问题描述
我在 SO 上使用了另一个答案,以便能够将 HTML 字符串转换为在 excel 中显示的富文本。
但是,它带来了一个令人讨厌的副作用,即无法在单个单元格中添加多行数据(我发现的建议是删除粘贴逻辑)。
理想情况下,我不想在我的解决方案中使用 Internet Explorer 的 CreateObject,而只是让粘贴正常工作。
这是使用字典找到的代码,该字典将粘贴到每个单元格。
如何完成将 HTML 字符串转换为文本并将多行粘贴到单个单元格?
' Sort By Years Descending
Dim yearKey As Variant
Dim firstYear As Boolean
Dim cellData As String
firstYear = True
cellData = "<HTML><DIV>"
For Each yearKey In stakeholderEvents(stakeholder).Keys
If Not firstYear Then
cellData = cellData & "<DIV></DIV>" ' Add Extra Blank Line
End If
cellData = cellData & "<B>" & yearKey & "</B>" & "<UL>" ' Add Year
' Loop Through Events For Year
Dim eventItem As Variant
For Each eventItem In stakeholderEvents(stakeholder)(yearKey)
cellData = cellData & "<LI>" & eventItem & "</LI>"
Next
cellData = cellData & "</UL>"
firstYear = False
Next
cellData = cellData & "<DIV></BODY></HTML>"
Set clipboardData = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
clipboardData.SetText cellData
clipboardData.PutInClipboard
Sheet1.Activate
'Sheet1.Range (Sheet1.Cells(rowIndex, stakeholderEventsColumn).Address)
Sheet1.Cells(rowIndex, stakeholderEventsColumn).Select
'Sheet1.Cells(rowIndex, stakeholderEventsColumn).Select
Sheet1.PasteSpecial Format:="Unicode Text"
解决方案
HTML 替代方案(参考Excel 友好的 html:将列表保存在单个单元格中):
Set clipboardData = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
clipboardData.SetText "<table><style>br {mso-data-placement:same-cell}</style><tr><td>" _
& "<b>Line 1</b><br>Line 2<br>Line 3"
clipboardData.PutInClipboard
Sheet1.Range("b2").PasteSpecial
XML 替代方案(可以通过分析.Value(11)
格式化单元格来调整 XML):
Dim c As Range
Set c = Sheet1.Range("b2")
c.Value = vbLf
c.Value(11) = Replace(c.Value(11), "<Data ss:Type=""String""> </Data>", _
"<ss:Data ss:Type=""String"" xmlns=""http://www.w3.org/TR/REC-html40"">" & _
"<B>Line 1</B> Line 2 Line 3</ss:Data>")
推荐阅读
- jsx - After Effects 从 JSX 更改表达式变量
- vue.js - vue 2 @click 处理程序未按预期工作
- shell - 为多个输入参数文件调用 jar 的 Cron 作业
- php - Composer 使用 OR 运算符更新包到特定版本
- c# - 如何从带有连接表的数据库动态创建 WPF 窗口?
- sql-server - 在一个数据库中检查约束失败
- java - 当我传递 URI 时,音乐文件可以正常工作,但是当我传递字符串路径时它不起作用。为什么?
- python - 如何使用Python在多个进程中运行pycuda
- android - 如何在通过 Apply{} 启动处理程序及其可运行对象时停止它
- angular - 类型 'import("/@types/chart.js/index.d.ts")' 缺少类型 'any[]' 的以下属性:length、pop、push、concat 和另外 26 个