2012-10-11 77 views
0

我在Excel中的宏从每一行读取数据并基于该数据为每行创建一个字文件。用作模板的单词文件具有书签(列中的值映射到书签)。Excel到Word(VB)通过行循环

我得到它为一行工作,但它不会遍历所有行。 HTTP://www.wiseowl.co.uk/blog/s199/word-bookmarks.htm

这里是我的代码:我用我的代码有

Option Explicit 

'change this to where your files are stored 

Const FilePath As String = "C:\Files\" 

Dim wd As New Word.Application 

Dim SOPCell As Range 

Sub CreateWordDocuments() 

    'create copy of Word in memory 

    Dim doc As Word.Document 

    wd.Visible = True 

    Dim SOPRange As Range 

    'create a reference to all the people 

    Range("A1").Select 

    Set SOPRange = Range(ActiveCell, ActiveCell.End(xlDown)).Cells 


    'for each person in list � 

    For Each SOPCell In SOPRange 

     'open a document in Word 

     Set doc = wd.Documents.Open(FilePath & "template.doc") 

     'go to each bookmark and type in details 

     CopyCell "sop", 0 
     CopyCell "equipment", 1 
     CopyCell "component", 2 
     CopyCell "step", 3 
     CopyCell "form", 4 
     CopyCell "frequency", 5 
     CopyCell "frequencyB", 5 

     'save and close this document 

     doc.SaveAs2 FilePath & "SOP " & SOPCell.Value & ".doc" 

     doc.Close 

    Next SOPCell 

    wd.Quit 

    MsgBox "Created files in " & FilePath & "!" 

End Sub 

Sub CopyCell(BookMarkName As String, ColumnOffset As Integer) 

    'copy each cell to relevant Word bookmark 

    wd.Selection.GoTo What:=wdGoToBookmark, Name:=BookMarkName 

    wd.Selection.TypeText SOPCell.Offset(0, ColumnOffset).Value 

End Sub 
+0

列A中行之间是否有空单元?这将阻止你的SOPRange被正确定义。 – nutsch

回答

0

你似乎在您的copyCell中忽略范围参数Sub

Sub CreateWordDocuments() 

    'create copy of Word in memory 

    Dim doc As Word.Document 
    wd.Visible = True 
    Dim SOPRange As Range 
    'create a reference to all the people 

    Set SOPRange = Range(Range("A1"), Range("A1").End(xlDown)).Cells 

    'for each person in list 

    For Each SOPCell In SOPRange 
     'open a document in Word 
     Set doc = wd.Documents.Open(FilePath & "template.doc") 
     'go to each bookmark and type in details 
     CopyCell SOPCell, "sop", 0 
     CopyCell SOPCell, "equipment", 1 
     CopyCell SOPCell, "component", 2 
     CopyCell SOPCell, "step", 3 
     CopyCell SOPCell, "form", 4 
     CopyCell SOPCell, "frequency", 5 
     CopyCell SOPCell, "frequencyB", 5 
     'save and close this document 
     doc.SaveAs2 FilePath & "SOP " & SOPCell.Value & ".doc" 

     doc.Close 

    Next SOPCell 

    wd.Quit 

    MsgBox "Created files in " & FilePath & "!" 

End Sub 

Sub CopyCell(rg As Range, BookMarkName As String, ColumnOffset As Integer) 

    'copy each cell to relevant Word bookmark 

    wd.Selection.GoTo What:=wdGoToBookmark, Name:=BookMarkName 

    wd.Selection.TypeText rg.Offset(0, ColumnOffset).Value 

End Sub 
+0

作品感谢您的帮助! – mgalal