excel - 如何在保留格式的同时将表格从 Word 复制到 Excel
问题描述
我多年来一直在编写 VBA 代码,但这个确实令人头疼。
任务很简单- 将表格中的数据从 Microsoft Word 复制到 Microsoft Excel。
挑战:维护 Word 中数据的格式,包括项目符号列表和多个段落。更具体地说,我需要将 Word 表中的单元格中的所有格式化文本包含在相应 Excel 表中的单个单元格中。
我已经尝试过的解决方案,特别是我遇到困难的地方:
方法01:在Word中选择整个表格,在Excel中选择一个单元格,然后粘贴。
Sub Method01_CopyAndPaste()
ActiveDocument.Tables(1).Select
Documents(1).ActiveWindow.Selection.Copy
Cells(1, 1).Select
ActiveSheet.Paste
End Sub
方法 01 的问题:只要 Word 表中有多个段落,Excel 就会创建多行和合并单元格。
方法 02:循环遍历 Word 表,并将所有内容分配给 Array(变体)。然后循环遍历 Excel 表并将数组中的值分配到表中。
Sub Method02_Array()
Dim r As Integer
Dim c As Integer
Dim AryTblData(1 To 10, 1 To 10) As Variant
'Loop through the 10x10 Source table and assign all values to 2 dimensional array
For r = 1 To 10
For c = 1 To 10
AryTblData(r, c) = ActiveDocument.Tables(1).Cell(r + 1, c)
Next c
Next r
'Paste the array values into the activesheet starting at cell(1,1)
For r = 1 To 10
For c = 1 To 10
Cells(r, c) = WorksheetFunction.Clean(AryTblData(r, c))
Next c
Next r
End Sub
方法 02 的问题:不保留格式。具体来说,项目符号点不会出现在 Excel 表中。
方法03:使用Application.Sendkeys模拟手动到Word表格的一个单元格,复制,到Excel表格对应的单元格,粘贴,按{TAB}进入下一个单元格的过程,然后然后对表格中的单元格总数重复此过程。
Sub Method03_Sendkeys()
Dim r As Integer
Dim c As Integer
'Loop through the 3x3 Source table and simulate sending keys to copy and paste, cell by cell
For r = 1 To 3
For c = 1 To 3
'Activate Microsoft Word window
AppActivate ("word"), True
'Select the appropriate cell in the Word table (based on the For Loop)
ActiveDocument.Tables(1).Cell(r, c).Select
'In Word, copy the selection
Application.SendKeys "^c", True
'Activate Microsoft Excel window
'Note: I'm not sure why AppActivate ("excel") does not work, but
'for some reason Application.caption works for me.
AppActivate Application.Caption, True
'Select the appropriate cell in the active Excel worksheet (based on the For Loop)
Cells(r, c).Select
'In Excel, edit cell contents
Application.SendKeys "{F2}", True
'In Excel, Paste
Application.SendKeys "^v", True
'In Excel, Save changes to cell and move 1 cell to the right
Application.SendKeys "{TAB}", True
Next c
Next r
End Sub
方法 03 的问题:它仅适用于 1 个单元格,但是一旦我尝试复制和粘贴多个单元格,结果就是在多个单元格中一遍又一遍地使用相同的数据。
问题:这个任务甚至可以在 VBA 中实现吗?我很想找到一个简单而优雅的解决方案,但在这一点上,我会满足于一些可行的东西。
非常感谢你的帮助!
解决方案
要将 Word 或 pdf 中的多行粘贴到 Excel 中的单个单元格中 - 单击单元格,按 F2,然后粘贴文本。这将所有内容保存在一个单元格中。但是它不保留包括颜色和删除线在内的格式
推荐阅读
- postgresql - 重载下自动升级RDS实例类型?
- c++ - 打开 .EXR 文件时 OpenImageIO 崩溃
- java - Page Rank 算法计算错误的页面排名
- hyperledger-fabric - 为 hyperledger-composer 正确定义 ACL 规则以进行资源间访问
- data-science - 这是过拟合吗
- tensorflow - keras,使用 RNN 模型的 MNIST 分类,关于输出形状的问题
- angularjs - 基于焦点的angularjs格式字段
- css - 当早期字体已经具有该字符时,为什么 Chrome 会为 UTF-8 字形字符使用低阶字体?
- sql - 如果它们与父表具有相同的ID,如何获取所有子表数据
- ios - 从 UITableView 中删除行会导致部分标题问题?