循环通过Excel单元格并将它们写入Word

我在Excel中使用macros来循环单元格,并将数据写入Word中的模板。 一切工作都很好,直到我想添加更多的单元格来抓取数据。 一切仍然正常工作,除非一旦variables我有名字“j”得到25的价值,我得到一个错误说:“运行时错误5941”:集合的请求的成员不存在。

我玩过不同的行和列,以及每个组合的作品。 只有当“ j ”达到25时才会出现错误。 当它到达wrd.ActiveDocument.Tables(1).Rows(j) … line时失败。

 Sub Label_ExcelToWord_Single() 'Variable that stores file path for 'word template Dim strpath As String strpath = Cells(28, 8) 'opens Microsoft Word to edit template Call OpenWord Set wrd = GetObject(, "Word.Application") wrd.Visible = True wrd.Activate wrd.ActiveDocument.Close savechanges:=False wrd.Documents.Open strpath 'Variables used for loop data manipulation Dim k As Integer Dim j As Integer k = 1 j = 1 'Primary loop responsible for exporting Excel 'data to word template For Col = 1 To 3 For Row = 3 To 32 wrd.ActiveDocument.Tables(1).Rows(j).Cells(((Row - 3) Mod 7) + k).Range.Text = Cells(Row, Col) & vbCrLf & Cells(Row, Col) If k = 7 Then k = 0 j = j + 2 End If If Col = 3 Then If Row = 32 Then 'When we reach the last cell containing data exit routine Exit Sub End If End If k = k + 1 Next Next End Sub 

看起来像表可能没有足够的行。 如果是这样,一个暴力的方式是添加行,因为你需要他们:

 ... For Col = 1 To 3 For Row = 3 To 32 ' vvv new lines vvv Do While wrd.ActiveDocument.Tables(1).Rows.Count < j wrd.ActiveDocument.Tables(1).Rows.Add Loop ' ^^^ new lines ^^^ ... 

我还build议将jkRowCol重命名为更具描述性的名称。 您有Excel行/列索引和Word表格行/列索引,除非名称清晰,否则很容易让他们感到困惑。

(注:是的,上面的代码是缓慢,笨重,未优化,yadda yadda。希望这将有助于OP。:))

我认为在Word中使用DocVariables更容易,并将Excel数据单元格中的数据导入DocVariables。 最终的游戏大致相同,但我认为代码更容易设置和维护。

 Sub PushToWord() Dim objWord As New Word.Application Dim doc As Word.Document Dim bkmk As Word.Bookmark sWdFileName = Application.GetOpenFilename(, , , , False) Set doc = objWord.Documents.Open(sWdFileName) 'On Error Resume Next objWord.ActiveDocument.variables("FirstName").Value = Range("FirstName").Value objWord.ActiveDocument.variables("LastName").Value = Range("LastName").Value objWord.ActiveDocument.variables("AnotherVariable").Value = Range("AnotherVariable").Value objWord.ActiveDocument.Fields.Update 'On Error Resume Next objWord.Visible = True End Sub 

设置MS Word对象库的引用。