Word VBA
外觀
這是一個使用 Visual Basic for Applications 編寫 Microsoft Word 指令碼的食譜集合。
學習 Word VBA 的一個好方法是使用它的宏錄製功能。使用此功能,您可以告訴 Word 開始錄製,然後執行各種步驟,就像您在沒有宏錄製器的情況下工作一樣,最後,告訴 Word 停止錄製。Word 會錄製與您使用 Word GUI 執行的操作相對應的 VBA 程式碼。雖然程式碼在沒有修改的情況下通常無法有效地使用,但從它開始並進行修改可以節省大量時間,否則這些時間將花費在閱讀 VBA 文件上。
選單路徑
- Word 2007:檢視(選項卡)> 宏(組)> 宏按鈕下方的向下箭頭 > 錄製宏
- Word 2007:開發工具(選項卡)> 程式碼(組)> 錄製宏
連結
- 錄製或執行宏(Word 2007) at microsoft.com
- 建立宏(Word 2003) at microsoft.com
- 錄製宏以生成程式碼(Office 2000) at microsoft.com
您可以按如下方式插入和刪除文字
Selection.TypeText Text:="Inserted as if by typing on keyboard"
Selection.Delete 'Deleted the single char after cursor, or a non-empty selection
您可以按如下方式移動游標
Selection.MoveDown Unit:=wdLine
Selection.MoveRight Unit:=wdCell 'At the end of a row, moves to the next row
您可以按如下方式選擇文字區域
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
您可以按如下方式格式化文字,包括文字顏色、背景顏色和字型屬性
Selection.Font.Color = RGB(0, 0, 255) 'Foreground color AKA text color
Selection.Range.HighlightColorIndex = wdYellow 'Background color as highlight
Selection.Font.Name = "Verdana" 'Font face
Selection.Font.Size = 8 'Font size
Selection.Font.Bold = True 'Or False
Selection.Font.Bold = wdToggle
Selection.Font.Italic = True
Selection.Font.Underline = True
您可以按如下方式複製和貼上
Selection.Copy
Selection.Paste
先決條件:從 Word 文件訪問剪貼簿需要在文件中設定對 MSForms(Microsoft Forms Object Library)的引用。您可以透過新增和隨後刪除使用者窗體來設定引用,方法是在彈出選單中透過“插入”>“使用者窗體”。要檢查引用是否存在,請參閱“工具”>“引用”選單。
將文字放置在剪貼簿中
Set MyClipboard = New MSForms.DataObject
MyClipboard.SetText "My string"
MyClipboard.PutInClipboard
從剪貼簿獲取文字
Set MyClipboard = New MSForms.DataObject
MyClipboard.GetFromClipboard
TextContent = MyClipboard.GetText
連結
- DataObject 類 at msdn.microsoft.com;包含關於 Visual Basic 的一部分,其對 Word VBA 的適用性尚不清楚。
Sub PasteTabSeparatedPlainTextToTable()
'This paste prevents loss of formatting of the table cells
Set MyClipboard = New MSForms.DataObject
MyClipboard.GetFromClipboard
TextContent = MyClipboard.GetText
SplitArray = Split(TextContent, vbNewLine)
For Each Element In SplitArray
SplitArray2 = Split(Element, vbTab)
TabSkipNeeded = False
Set OldSelection = Selection.Range
For Each CellContent In SplitArray2
If TabSkipNeeded Then
Selection.MoveRight Unit:=wdCell
Else
TabSkipNeeded = True
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
End If
Selection.TypeText Text:=CellContent
Next
OldSelection.Select
Selection.MoveDown Unit:=wdLine
Next
End Sub
- Word VBA 參考, docs.microsoft.com
- 標籤 ms-word 和 vba, stackoverflow.com