ExcelHome技术论坛

 找回密码
 免费注册

QQ登录

只需一步,快速开始

快捷登录

搜索
EH技术汇-专业的职场技能充电站 妙哉!函数段子手趣味讲函数 Excel服务器-会Excel,做管理系统 Excel Home精品图文教程库
HR薪酬管理数字化实战 Excel 2021函数公式学习大典 Excel数据透视表实战秘技 打造核心竞争力的职场宝典
300集Office 2010微视频教程 数据工作者的案头书 免费直播课集锦 ExcelHome出品 - VBA代码宝免费下载
用ChatGPT与VBA一键搞定Excel WPS表格从入门到精通 Excel VBA经典代码实践指南
查看: 294|回复: 4

[求助] 求大神幫助 - 有關Word VBA 的問題

[复制链接]

TA的精华主题

TA的得分主题

发表于 2023-4-19 17:37 | 显示全部楼层 |阅读模式
本帖最后由 terenceli35 于 2023-4-19 17:41 编辑

大家好,最近我打算寫一個Word VBA ,根據一個Excel 檔案中的名單,複製一份Word 文件中的文字到另一個Excel 檔案。

步驟如下:

1. 運行宏(Macro),首先彈出視窗,選擇要貼上複製文字的Excel 檔案。

2. 宏(Macro) 會在已打開的文件中,按一個Excel 檔案中的名單,複製Word 文件中的文字。

3. 在步驟1選擇的Excel 檔案貼上複製文字。

4. 彈出複製的Excel 檔案。

以下是暫時的code:

Option Explicit

Private xlWB1 As String
Private xlWB2 As String
Private xlSheet As String

Sub CopyText_from_Word_to_Excel()

Dim EXL As Object
Dim xlsWB1 As Object
Dim xlsWB2 As Object
Dim xlsPath As String
Dim oDoc As Document
Dim oRng As Range
Dim Arr() As Variant

xlsWB1 = "D:\databases\ENG.xlsx"

xlWB2 = BrowseForFile("Select Workbook", True)
If Not xlWB2 = vbNullString Then

xlSheet = "sheet1"

    Set EXL = CreateObject("Excel.Application")
    Set oDoc = ActiveDocument
    Set oRng = oDoc.Range
    Arr = xlFillArray(xlWB1, xlSheet)
   
    With oRng.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Font.Name = "Times New Roman"
        .Font.Bold = True
        
        Do While .Execute()
        
        If oRng.Text = Arr Then
                  WriteToWorksheet xlWB1, xlSheet, oRng.Text
            End If
        Loop

    End With
   
lbl_Exit:
    Exit Sub
    End If
   
            Set xlsWB2 = EXL.Workbooks.Open(xlWB2)
    EXL.Visible = True
   
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
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 Function xlFillArray(strWorkbook As String, _
                             strRange As String) As Variant

Dim RS As Object
Dim CN As Object
Dim iRows As Long

strRange = strRange & "$]"    'Use this to work with a named worksheet
    'strRange = strRange & "]" 'Use this to work with a named range
    Set CN = CreateObject("ADODB.Connection")

    'Set HDR=NO for no header row
    CN.Open ConnectionString:="Provider=Microsoft.ACE.OLEDB.12.0;" & _
                              "Data Source=" & strWorkbook & ";" & _
                              "Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"""

    Set RS = CreateObject("ADODB.Recordset")
    RS.Open "SELECT * FROM [" & strRange, CN, 2, 1

    With RS
        .MoveLast
        iRows = .RecordCount
        .MoveFirst
    End With
    xlFillArray = RS.GetRows(iRows)
    If RS.State = 1 Then RS.Close
    Set RS = Nothing
    If CN.State = 1 Then CN.Close
    Set CN = Nothing
lbl_Exit:
    Exit Function
End Function

  1. <blockquote>Option Explicit
复制代码


不知道為什麼,"If oRng.Text = Arr Then" 形態總是不符合。

請問怎樣才能令 VBA 根據一個Excel 檔案中的名單複製一份Word 文件中的文字到另一個Excel 檔案?

小弟請求各位大神幫忙,感激萬分!





TA的精华主题

TA的得分主题

 楼主| 发表于 2023-4-19 17:38 | 显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件       ★免费下载 ★       ★ 使用帮助
CODE在這裡,不知道為什麼原帖不能貼上CODE

Option Explicit

Private xlWB1 As String
Private xlWB2 As String
Private xlSheet As String

Sub CopyText_from_Word_to_Excel()

Dim EXL As Object
Dim xlsWB1 As Object
Dim xlsWB2 As Object
Dim xlsPath As String
Dim oDoc As Document
Dim oRng As Range
Dim Arr() As Variant

xlsWB1 = "D:\databases\ENG.xlsx"

xlWB2 = BrowseForFile("Select Workbook", True)
If Not xlWB2 = vbNullString Then

xlSheet = "sheet1"

    Set EXL = CreateObject("Excel.Application")
    Set oDoc = ActiveDocument
    Set oRng = oDoc.Range
    Arr = xlFillArray(xlWB1, xlSheet)
   
    With oRng.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Font.Name = "Times New Roman"
        .Font.Bold = True
        
        Do While .Execute()
        
        If oRng.Text = Arr Then
                  WriteToWorksheet xlWB1, xlSheet, oRng.Text
            End If
        Loop

    End With
   
lbl_Exit:
    Exit Sub
    End If
   
            Set xlsWB2 = EXL.Workbooks.Open(xlWB2)
    EXL.Visible = True
   
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
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 Function xlFillArray(strWorkbook As String, _
                             strRange As String) As Variant

Dim RS As Object
Dim CN As Object
Dim iRows As Long

strRange = strRange & "$]"    'Use this to work with a named worksheet
    'strRange = strRange & "]" 'Use this to work with a named range
    Set CN = CreateObject("ADODB.Connection")

    'Set HDR=NO for no header row
    CN.Open ConnectionString:="Provider=Microsoft.ACE.OLEDB.12.0;" & _
                              "Data Source=" & strWorkbook & ";" & _
                              "Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"""

    Set RS = CreateObject("ADODB.Recordset")
    RS.Open "SELECT * FROM [" & strRange, CN, 2, 1

    With RS
        .MoveLast
        iRows = .RecordCount
        .MoveFirst
    End With
    xlFillArray = RS.GetRows(iRows)
    If RS.State = 1 Then RS.Close
    Set RS = Nothing
    If CN.State = 1 Then CN.Close
    Set CN = Nothing
lbl_Exit:
    Exit Function
End Function

TA的精华主题

TA的得分主题

发表于 2023-4-20 12:40 | 显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件       ★免费下载 ★       ★ 使用帮助
本帖最后由 batmanbbs 于 2023-4-20 12:42 编辑

不会EXCEL,不过看上去Arr是个二维数组,不能直接和.text进行比较,需要加上索引(或者叫下标),比如Arr(0)(1) 【这个是WORD的写法】

TA的精华主题

TA的得分主题

 楼主| 发表于 2023-4-20 23:36 | 显示全部楼层
batmanbbs 发表于 2023-4-20 12:40
不会EXCEL,不过看上去Arr是个二维数组,不能直接和.text进行比较,需要加上索引(或者叫下标),比如Arr(0 ...

可以示範一下嗎?不太明白。

TA的精华主题

TA的得分主题

发表于 2023-4-21 16:59 | 显示全部楼层
本帖最后由 batmanbbs 于 2023-4-21 17:02 编辑
  1.         Do While .Execute()
  2.         
  3.         If oRng.Text = Arr Then
  4.                   WriteToWorksheet xlWB1, xlSheet, oRng.Text
  5.             End If
  6.         Loop
复制代码


你的代码中这段中的 oRng.Text = Arr ,其中Arr应该是一个二维数组,如果要比较,打个比方应该是 oRng.Text = Arr(0)(0) ,Arr(0)(0)代表二维数组中的第一个数据
您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

手机版|关于我们|联系我们|ExcelHome

GMT+8, 2024-5-19 21:44 , Processed in 0.031327 second(s), 10 queries , Gzip On, MemCache On.

Powered by Discuz! X3.4

© 1999-2023 Wooffice Inc.

沪公网安备 31011702000001号 沪ICP备11019229号-2

本论坛言论纯属发表者个人意见,任何违反国家相关法律的言论,本站将协助国家相关部门追究发言者责任!     本站特聘法律顾问:李志群律师

快速回复 返回顶部 返回列表