嗨,我是一个优秀VBA的人,如果有人能帮我解决这个问题,我会非常感激。 我花了5天多的时间进行研究和阅读,试图解决这个问题并且无法获得所需的结果,任何人都可以帮忙。 我正在使用userform将数据提交到工作表,然后使用上面的vba打开一个单词模板,动态选择工作表的最后一行,并将选定的单元格数据输入到单词模板中各种占位符书签的预先存在的表中。 代码始终将数据粘贴到表格上方而不是粘贴在表格中。 这是我使用
的代码Sub testdata()
'declare variables
Dim wdDoc As Word.Document
Dim wdApp As Word.Application
'declare variable for save format
Dim savename As String
'declare fileext type for differnt versions of word
Dim fileext As String
'start word
Set wdApp = New Word.Application
'make it visible and activate it
With wdApp
'uncomment 2 lines below to see word on screen
.Visible = True
.Activate
'opens a word doc
.Documents.Add "C:\xxx\xxx\excel_project\test.docx"
'collect data range ref number
Range("A1").End(xlDown).Copy
'selects the item bookmark in word template
.Selection.GoTo What:=-1, Name:="Item"
'paste into word doc
.Selection.Paste
'test version type of word
If .Version <= 11 Then
fileext = ".doc"
Else
fileext = ".docx"
End If
'saves doc with specific timedate name
savename = "C:\xxx\xxx\excel_project\test" & _
Format(Now, "dd-mm-yyyy hh-mm-ss") & fileext
'changes save as method depended on word version
If .Version <= 12 Then
.ActiveDocument.SaveAs savename
Else
.ActiveDocument.SaveAs2 savename
End If
'closes the doc
.ActiveDocument.Close
'closes word
.Quit
End With
End Sub
建议使用的一个帮助来源 `
Sub FnBookMarkInsertAfter()
Dim objWord
Dim objDoc
Dim objRange
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("C:\xxx\xxx\excel_project\test.docx")
objWord.Visible = True
Set objRange = objDoc.Bookmarks("item").Range
objRange.InsertAfter ("..........I will be added AFTER bookmark")
End Sub
` 这会将文本字符串放入表中,我无法找到一种方法使其动态选择最后一行,从而选择所需的数据。
非常感谢任何帮助
答案 0 :(得分:0)
此代码在表的最后一行下方插入一行。书签&#34;项目&#34;必须位于你的桌子内,然后这将工作。字符串col1和col2插入新行的单元格中。希望这会对你有所帮助。
Sub InsertTextAtEndOfTable()
Application.ScreenUpdating = False
Dim col1, col2 As String
col1 = "TitleColContent"
col2 = "ValueColContent"
Selection.GoTo What:=wdGoToBookmark, Name:="Item"
Dim tabSize As Integer
tabSize = Selection.Tables(1).Rows.Count
Selection.Tables(1).Cell(1, 1).Select
Dim i As Integer
For i = 1 To tabSize - 1
Selection.MoveDown Unit:=wdLine, Count:=1
Next i
Selection.InsertRowsBelow
Selection.TypeText col1
Selection.MoveRight
Selection.TypeText col2
Application.ScreenUpdating = True
End Sub