|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
大家好,请问如何写一个宏命令,按一个Excel名单复制Word文件内的文字,然后在选定的Excel 贴上?
例如在一个Word文件中,有以下对话:
陈大文:大家好,我是陈大文
李小明:请坐。
陈大文:好的。
陈月:好的。
李小明:请用1分钟介绍一下自己。
陈大文:我是陈大文,毕业于XXX......
陈月:我是陈月,毕业于XXX......
我希望写一个宏命令,做到以下的步骤:
1. 选取指定的Excel档案。
(以下两组代码可做到弹出视窗,让用家选取指定的Excel档案)
- Private Function BrowseForFile(Optional strTitle As String, Optional bExcel As Boolean) As String
- Dim fDialog As FileDialog
- On Error GoTo err_Handler
- Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
- With fDialog
- .Title = strTitle
- .AllowMultiSelect = False
- .Filters.Clear
- If bExcel Then
- .Filters.add "Excel workbooks", "*.xls,*.xlsx,*.xlsm"
- Else
- .Filters.add "Word documents", "*.doc,*.docx,*.docm"
- End If
- .InitialView = msoFileDialogViewList
- If .Show <> -1 Then GoTo err_Handler:
- BrowseForFile = fDialog.SelectedItems.Item(1)
- End With
- lbl_Exit:
- Exit Function
- err_Handler:
- BrowseForFile = vbNullString
- Resume lbl_Exit
- End Function
复制代码- Private strWorkbook As String
- Private strSheet As String
- strWorkbook = BrowseForFile("Select Workbook", True)
- If Not strWorkbook = vbNullString Then
- strSheet = "sheet1"
复制代码
2. 自动复制上述对话中的粗体字,字型是"新细明体"。
3. 自动在刚才选定的Excel 档案由Cell B3开始贴上。
我暂时只有以下的Macro,该Macro只能自动复制 "Speaker 1", "Speaker 2", "Speaker 3" 到指定的Excel 档案。
- Option Explicit
- Private Const xlWB As String = "C:\Path\Empty Excel File name.xlsx"
- Private Const xlSheet As String = "Sheet1"
- Sub ExtractText()
- Dim oDoc As Document
- Dim oRng As Range
- Set oDoc = ActiveDocument
- Set oRng = oDoc.Range
- With oRng.Find
- .ClearFormatting
- .Replacement.ClearFormatting
- .Font.Name = "Times New Roman"
- .Font.Bold = True
- Do While .Execute()
- If oRng.Text Like "Speaker*" Then
- WriteToWorksheet xlWB, xlSheet, oRng.Text
- End If
- Loop
- End With
- lbl_Exit:
- Exit Sub
- End Sub
- Private Function WriteToWorksheet(strWorkbook As String, _
- strRange As String, _
- strValues As String)
- Dim ConnectionString As String
- Dim strSQL As String
- Dim CN As Object
- ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
- "Data Source=" & strWorkbook & ";" & _
- "Extended Properties=""Excel 12.0 Xml;HDR=YES;"";"
- strSQL = "INSERT INTO [" & strRange & "$] VALUES('" & strValues & "')"
- Set CN = CreateObject("ADODB.Connection")
- Call CN.Open(ConnectionString)
- Call CN.Execute(strSQL, , 1 Or 128)
- CN.Close
- Set CN = Nothing
- lbl_Exit:
- Exit Function
- End Function
复制代码 请问有大师可以帮助小弟吗?感激万分
|
|