查找Excel电子表格和VBA阵列之间的匹配项

时间:2017-06-14 19:20:43

标签: excel vba excel-vba ms-word

我是Excel VBA的新手,正在寻找一些修复我的代码的帮助。所以基本上为我提供的颜色,我有一个Excel数据库和一个word文档。在单词文档中,我已经将标题部分标记为(" cat"," dog"和" bird"),并且在excel数据库中连续写入I有"狗"和#34;鸟"。

我要做的是编写一个代码,将数组的元素(字符串)与excel数据库中声明的范围内的单元格值进行比较。对于数组中存在但未在声明的excel范围内的值,我想从word文档中删除这些值(即书签)。

如果有人能够向我提供反馈,想法或示例代码,我们将不胜感激。

感谢。

Sub ArrayToDatabase()

Dim myRange As Variant
Set myRange = Range("C7:AP7")

Dim myArray As Variant
myArray = Array("cat", "dog", "bird")

Dim i As Integer
Dim reqName As Object
For i = LBound(myArray) To UBound(myArray)
    Set reqName = myArray(i).Value
    If myRange.Validation(reqName) = False Then
        wdApp.ActiveDocument.Bookmarks(reqName).Range._
        Paragraphs(1).Range.Delete
    End If
Next i

End Sub

2 个答案:

答案 0 :(得分:3)

<强>逻辑

  1. 使用.Find检查关键字是否存在于范围内。
  2. 将相关关键字存储在逗号分隔的字符串中,以后将转换为数组
  3. 打开word doc
  4. 循环播放数组并删除书签
  5. 这是你在尝试的吗?

    Option Explicit
    
    Sub Sample()
        Dim myArray As Variant, BookMarksToDelete As Variant
        Dim oWordApp As Object, oWordDoc As Object
        Dim sTemp As String, FlName As String
        Dim aCell As Range, myRange As Range
        Dim i As Long
    
        '~~> Change this to the relevant sheet
        Set myRange = ThisWorkbook.Sheets("Sheet1").Range("C7:AP7")
    
        myArray = Array("cat", "dog", "bird")
    
        '~~> Change this to the relevant word document
        FlName = "C:\Users\Siddharth\Desktop\DeleteMeLater.docx"
    
        For i = LBound(myArray) To UBound(myArray)
            '~~> Check if the word exists in the range or not
            Set aCell = myRange.Find(What:=myArray(i), LookIn:=xlValues, _
                        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                        MatchCase:=False, SearchFormat:=False)
            '~~> If it doesn't then store it in a comma delimited string
            If aCell Is Nothing Then
                sTemp = sTemp & "," & myArray(i)
            Else
                Set aCell = Nothing
            End If
        Next i
    
        sTemp = Mid(sTemp, 2)
    
        If Not Len(Trim(sTemp)) = 0 Then
            '~~> Convert comma delimited string to array
            BookMarksToDelete = Split(sTemp, ",")
    
            '~~> Open word document
            Set oWordApp = CreateObject("Word.Application")
            oWordApp.Visible = True
            Set oWordDoc = oWordApp.Documents.Open(FlName)
    
            '~~> Delete the bookmarks
            For i = LBound(BookMarksToDelete) To UBound(BookMarksToDelete)
                oWordDoc.Bookmarks(BookMarksToDelete(i)).Delete
            Next i
        End If
    
        MsgBox "Done"
    End Sub
    

答案 1 :(得分:0)

您的代码是否有效?它有点不清楚你要问的是什么,除非这仅仅是为了反馈。我个人不得不说的是你声明变量的方式。

因此,如果您知道该变量将保留什么,最好将其声明为此类。例如,

Dim myRange as Range

Dim myArray(2) as String
myArray = {"cat", "dog", "bird"}

Dim reqName as String

我也没有专家,只是想帮忙!随意提出任何问题,但我不能保证我有答案。