如何将文本中的数据从excel导出为文本使用VBA

我从这个网站find了下面的代码。 它几乎工作,除了它将date导出到Word文档中的窗体。 相反,我想有段落,保持原来的字体,大小和颜色在Excel中。 谁能帮忙? 非常感谢!

Sub Export_Excel_To_Word() Dim wdApp As Object Dim wd As Object On Error Resume Next Set wdApp = GetObject(, "Word.Application") If Err.Number <> 0 Then Set wdApp = CreateObject("Word.Application") End If On Error GoTo 0 Set wd = wdApp.Documents.Add wdApp.Visible = True Sheets("sheet1").Activate Set Rng = ThisWorkbook.ActiveSheet.Range("A2:F21") Rng.Copy With wd.Range .Collapse Direction:=wdCollapseStart 'Slutet av dokumentet .InsertParagraphAfter 'Lagg till rad .Collapse Direction:=wdCollapseStart 'Slutet av dokumentet .PasteSpecial xlPasteFormats, False, False 'Paste with format End With End Sub 

这很简单,你正在使用pasteSpecial方法,并放错了参数。 这在一开始就引起了我的错误。 试试这个来粘贴纯粹的无格式文本:

 .PasteSpecial DataType:=2 ' wdPasteDataType.wdPasteText 

或者保持字体的格式,

 .PasteSpecial DataType:=1 ' wdPasteDataType.wdPasteRtf 

粘贴后用单个空格replace标签:

 With wd.Range .Collapse Direction:=wdCollapseStart .InsertParagraphAfter .Collapse Direction:=wdCollapseStart .PasteSpecial DataType:=2 With .Find .ClearFormatting .Text = vbTab .Replacement.ClearFormatting .Replacement.Text = " " .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue End With End With 

我能想到的最简单的方法是粘贴Excel范围并将表格转换为文本:

 ThisWorkbook.Sheets("sheet1").Range("A2:F21").Copy wdApp.Selection.Paste wdApp.DefaultTableSeparator = " " wdApp.Selection.Previous(15).Rows.ConvertToText