查找Excel电子表格和VBA数组之间的匹配

我是新的Excel VBA,并寻求一些帮助,以解决我的代码。 所以基本上提供了我所拥有的颜色,我有一个excel数据库和一个word文档。 在单词文件中,我已经添加了书签的章节标题(被改为“猫”,“狗”和“鸟”),并在excel数据库中有一行“狗”和“鸟”。

我想要做的是写一个代码比较数组的元素(这是string)的单元格值在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 

逻辑

  1. 使用。查找来检查关键字是否在范围内。
  2. 将相关关键字存储在以逗号分隔的string中,稍后将转换为数组
  3. 打开word文档
  4. 循环访问数组并删除书签

这是你正在尝试?

 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 

你的代码是否工作? 这是有点不清楚你问的,除非这只是反馈。 我个人不得不说的是你声明variables的方式。

所以如果你知道这个variables是什么的话,最好把它声明为这样。 例如,

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

我也不是专家,只是想帮助! 随意问任何问题,但我不能保证我有一个答案。