簡介
比如我有一個需求,需要把一份 word 中的英文國家名全部替換成中文國家名,excel中的第一列是英文國家名,第二列是中文國家名。人工完成的話,費時費力,使用我編寫的程序,雙擊一下,瞬間完成。
文章目錄
效果圖 處理前
處理后
源碼
Const wdReplaceAll = 2
Dim arrSheet()
Dim nUsedRows, nUsedCols
Dim wordPath, exelPath
'將下面這一行代碼的雙引號中的內容替換成你的word文檔地址
wordPath = ("D:\Tecent\QQFile\123.docx")
'將下面這一行代碼的雙引號中的內容替換成你的excel文檔地址
exelPath = ("D:\Tecent\QQFile\123.xlsx")
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Open(wordPath)
Set objSelection = objWord.Selection
objSelection.Find.Forward = TRUE
objSelection.Find.MatchWholeWord = TRUE
ReadExcelFile(exelPath)
for i=0 to nUsedRows-1
objSelection.Find.Text = arrSheet(i,0)
objSelection.Find.Replacement.Text = arrSheet(i,1)
objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll
next
Function ReadExcelFile(ByVal strFile)
' Local variable declarations
Dim objExcel, objSheet, objCells
Dim nTop, nLeft, nRow, nCol
' Default return value
ReadExcelFile = Null
' Create the Excel object
On Error Resume Next
Set objExcel = CreateObject("Excel.Application")
If (Err.Number <> 0) Then
Exit Function
End If
' Don't display any alert messages
objExcel.DisplayAlerts = 0
' Open the document as read-only
On Error Resume Next
Call objExcel.Workbooks.Open(strFile, False, True)
If (Err.Number <> 0) Then
Exit Function
End If
' If you wanted to read all sheets, you could call
' objExcel.Worksheets.Count to get the number of sheets
' and the loop through each one. But in this example, we
' will just read the first sheet.
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)
' Get the number of used rows
nUsedRows = objSheet.UsedRange.Rows.Count
' Get the number of used columns
nUsedCols = objSheet.UsedRange.Columns.Count
' Get the topmost row that has data
nTop = objSheet.UsedRange.Row
' Get leftmost column that has data
nLeft = objSheet.UsedRange.Column
' Get the used cells
Set objCells = objSheet.Cells
' Dimension the sheet array
ReDim arrSheet(nUsedRows - 1, nUsedCols - 1)
' Loop through each row
For nRow = 0 To (nUsedRows - 1)
' Loop through each column
For nCol = 0 To (nUsedCols - 1)
' Add the cell value to the sheet array
arrSheet(nRow, nCol) = objCells(nRow + nTop, nCol + nLeft).Value
Next
Next
' Close the workbook without saving
Call objExcel.ActiveWorkbook.Close(False)
' Quit Excel
objExcel.Application.Quit
' Return the sheet data to the caller
ReadExcelFile = arrSheet
End Function
使用說明 excel 表格的 A 列是待替換內容批量替換word文件內容,B 列是替換后的內容新建txt文檔,復制粘貼源碼,將代碼中第7行的 的值修改為你的word文檔的路徑地址。將代碼中第9行的 的值修改為你的 excel 文檔的路徑地址。修改文檔后綴為VBS批量替換word文件內容,點確認。修改完成后,你將得到一個xxx.VBS的可執行程序,雙擊即可完成替換操作。后續有什么問題,可在評論區留言。我看到后會盡快回復。 參考資料
《How Can I Text in a Word ?》
《 Excel Files》