Board logo

標題: 用excel vba 控制word 並將userform的資料填入word的表格中 [打印本頁]

作者: ciboybj    時間: 2019-7-30 22:22     標題: 用excel vba 控制word 並將userform的資料填入word的表格中

本帖最後由 ciboybj 於 2019-7-30 22:25 編輯

大家好:)
我寫了一個小程式在Excel VBA中
主要是有一個Userform 裡面有一個『按鈕』,使用者按下『按鈕』後
vba會開啟同一路徑下名為『範本』的word檔
開啟word檔後,將尋找 word檔案中的『 編號』 字串,找到『 編號』 的字串後,向右邊移動兩個字元(移到隔壁的格子中),並插入userform中某一個標間的字串
  1. Private Sub CommandButton2_Click()

  2.     Dim path As String
  3.     path = ThisWorkbook.path & "\範本.docx"
  4.     'Debug.Print (path)

  5.     Set WordApp = CreateObject("Word.Application")
  6.     WordApp.Documents.Open (path)
  7.     WordApp.Visible = True
  8.     WordApp.Activate
  9.     WordApp.Selection.homekey unit:=6
  10.    
  11.     WordApp.Selection.Find.Execute FindText:="編號" ', Forward:=True, Wrap:=wdFindStop
  12.     WordApp.Selection.MoveRight = 2
  13.     WordApp.Selection.InsertAfter = LB_Num.Caption
  14.    
  15. End Sub
複製代碼
但是,我執行上面的程式碼後,出現了以下的錯誤訊息
[attach]31096[/attach]

想請問大家
為何有上面的錯誤訊息 我要怎麼修改程式才可以運作阿∼∼∼{:3_50:}
[attach]31097[/attach]
作者: ciboybj    時間: 2019-8-1 21:18

目前找到的解決方式是:
在vba的工具列中選擇『工具』->『設定引用項目』
把Microsoft Word 的項目勾起
[attach]31107[/attach][attach]31107[/attach]

程式碼的部分如下:
  1. Private Sub CommandButton1_Click()
  2.    
  3.    Dim str As String
  4.     str = TextBox1.Text

  5.     Dim WordApp As Word.Application
  6.     Set WordApp = New Word.Application

  7.     WordApp.Documents.Open ThisWorkbook.Path & "\test.docm"
  8.     WordApp.Visible = True
  9.    
  10.     WordApp.Selection.Find.Execute FindText:="編號"
  11.     WordApp.Selection.Move Unit:=wdCell, Count:=1
  12.     WordApp.Selection.InsertAfter str
  13.     WordApp.Documents.Save
  14.    
  15.     Set WordApp = Nothing
  16. End Sub
複製代碼
由於在word中找到的字是在表格中,因此,要用wdCell 這個移動單位來移動鼠標位置




歡迎光臨 麻辣家族討論版版 (http://forum.twbts.com/)