2016-11-21 47 views
0

我試圖弄清楚如何將插入TextBox的值複製到Userform中。我希望插入Userform的所有值都保存在使用書籤的doc文件中。如何從Excel 2013中的Userform中將TextBox的值複製到使用書籤的doc文件中?

這裏是我的代碼:

Sub report() 
    Dim wrdApp As Word.Application 
    Set wrdApp = CreateObject("Word.Application") 

    With wrdApp 
     .documents.Open "C:\Users\ment_hoch.docx" 

     .Selection.GoTo What:=wdGoToBookmark, Name:="ab_name" 
     .Selection.TypeText text:=Me.TextBox1.text 
     'Not working 

     .Selection.GoTo What:=wdGoToBookmark, Name:="abteilung" 
     .Selection.TypeText text:=ComboBox1.Value 
     'Not working 
    End with 
End Sub 

回答

0

我用一個獨立的子(下)這 - 調整你的代碼:

Sub report() 
    Dim wrdApp As Word.Application, doc 
    Set wrdApp = CreateObject("Word.Application") 


    Set doc = wrdApp.documents.Open("C:\Users\ment_hoch.docx") 

    SetBookmarkText doc, "ab_name", Me.TextBox1.text 

    SetBookmarkText doc, "abteilung", ComboBox1.Value 

End Sub 


'Replace the text in a bookmark or insert text into an empty (zero-length) bookmark 
Sub SetBookmarkText(oDoc As Word.Document, sBookmark As String, sText As String) 

    Dim BMRange As Word.Range 

    If oDoc.Range.Bookmarks.Exists(sBookmark) Then 
     Set BMRange = oDoc.Range.Bookmarks(sBookmark).Range 
     BMRange.Text = sText 
     oDoc.Range.Bookmarks.Add sBookmark, BMRange 
    Else 
     MsgBox "Bookmark '" & sBookmark & "' not found in document '" & oDoc.Name & "'" & _ 
       vbCrLf & "Content not updated" 
    End If 

End Sub 
0

一些測試,我想通了,它完美之後當我使用UserForm1。而不是我

.Selection.GoTo什麼:= wdGoToBookmark,名稱:= 「ab_name」 .Selection.TypeText文本:= UserForm1.TextBox1.text

.Selection.GoTo什麼:= wdGoToBookmark,名稱: =「abteilung」 .Selection.TypeText文本:= UserForm1.ComboBox1.Value

非常感謝您的答覆:)我會嘗試還當我得到一些自由時間!

相關問題