请问用vba如何将excel的数据导入到word.
小弟今天才开始学习vba,想写一个宏。
功能是运行这个宏时,能够在当前路径生成一个与excel文件同名的word文档,并且将excel各单元格中的数据按行输入到word当中。
比如 excel中的两行数据
R1C1 R1C2 R1C3 R1C4
R2C1 R2C2 R2C3 R2C4
输出到word就成了
R1C1
R1C2
R1C3
R1C4
R2C1
R2C2
R2C3
R2C4
请各位原谅我这拙劣的表达方式,我确实是才开始接触,请各位高手指点,谢谢大家。
[解决办法]
将上面代码中的下面3句删除,它们多余了。
Dim lRows As Long, iCols As Integer
lRows = ActiveSheet.UsedRange.Rows.Count
iCols = ActiveSheet.UsedRange.Columns.Count
删除后的代码如下:
Sub 测试() Dim fPath As String Dim fName As String fPath = ActiveWorkbook.Path fName = ActiveWorkbook.Name Dim i As Integer Dim docName As String For i = 1 To Len(fName) If Mid(fName, i, 1) = "." Then Exit For Next i docName = fPath & Application.PathSeparator & Left(fName, i - 1) ActiveSheet.UsedRange.Copy Dim wdApp As Object Dim wdDoc As Object Set wdApp = CreateObject("word.application") wdApp.Visible = True Set wdDoc = wdApp.Documents.Add wdApp.Selection.PasteSpecial DataType:=2 wdApp.DisplayAlerts = False wdDoc.SaveAs Filename:=docName & ".doc" wdApp.DisplayAlerts = TrueEnd Sub
[解决办法]
修改了一下,楼主再试试
Sub 测试() Dim fPath As String Dim fName As String fPath = ActiveWorkbook.Path fName = ActiveWorkbook.Name Dim i As Integer Dim docName As String For i = 1 To Len(fName) If Mid(fName, i, 1) = "." Then Exit For Next i docName = fPath & Application.PathSeparator & Left(fName, i - 1) Dim vArray As Variant vArray = ActiveSheet.UsedRange Dim docContent As String Dim r As Long, c As Integer For r = 1 To UBound(vArray, 1) For c = 1 To UBound(vArray, 2) vArray(r, c) = vArray(r, c) & Chr(13) docContent = docContent & vArray(r, c) Next c Next r Dim wdApp As Object Dim wdDoc As Object Set wdApp = CreateObject("word.application") wdApp.Visible = True Set wdDoc = wdApp.Documents.Add wdApp.Selection.Typetext docContent wdApp.DisplayAlerts = False wdDoc.SaveAs Filename:=docName & ".doc" wdApp.DisplayAlerts = TrueEnd Sub