2017-06-14 72 views
1

我是Excel VBA的新手,並且正在尋求一些幫助來修復我的代碼。所以基本上要提供我所擁有的顏色,我有一個excel數據庫和一個word文檔。在word文檔中,我有書籤的章節標題(被改爲「cat」,「dog」和「bird」),並且在excel數據庫中有一行「dog」和「bird」。查找Excel電子表格和VBA數組之間的匹配

我想要做的是編寫一個代碼,將數組元素(它是字符串)與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 

回答

3

邏輯

  1. 使用.Find檢查,如果關鍵字存在於範圍或沒有。
  2. 商店以逗號分隔字符串相關的關鍵字,這將在稍後通過數組轉換成一個數組
  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 
+0

嗨Siddharth,謝謝你的迴應。所以我繼續運行你的代碼,並且下面一行提出了'運行時錯誤462'。 oWordDoc.Bookmarks(BookMarksToDelete(i))。刪除 –

+0

我的代碼已經過測試並嘗試過了:)順便說一下在我去健身房的路上,當我回來的時候必須要看這個,仔細檢查書籤是否存在,並且沒有任何額外的空格... –

+0

我明白了,再次感謝你。後來該行不只是刪除書籤,而且還刪除它的文本和它下面的段落?(即我有一個標題和一個段落)。 –

0

您的代碼是否正常工作?這是有點不清楚你問什麼,除非這只是反饋。我個人不得不說的就是你聲明變量的方式。

所以如果你知道變量將保持什麼,最好聲明它是這樣的。例如,

Dim myRange as Range 

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

Dim reqName as String 

我不是專家,只是試圖幫助!隨意問任何問題,但我不能保證我有答案。