Sub CreateKnowledgeDatabase()
' Create workbook structure
Dim wsVisible As Worksheet, wsHidden As Worksheet
Dim wsNameVisible As String, wsNameHidden As String
' Define sheet names
wsNameVisible = "SearchInterface"
wsNameHidden = "KnowledgeBase"
' Create or reference visible worksheet
On Error Resume Next
Set wsVisible = ThisWorkbook.Worksheets(wsNameVisible)
If wsVisible Is Nothing Then
Set wsVisible = ThisWorkbook.Worksheets.Add
wsVisible.Name = wsNameVisible
End If
wsVisible.Visible = xlSheetVisible
wsVisible.Activate
On Error GoTo 0
' Create or reference hidden worksheet
On Error Resume Next
Set wsHidden = ThisWorkbook.Worksheets(wsNameHidden)
If wsHidden Is Nothing Then
Set wsHidden = ThisWorkbook.Worksheets.Add
wsHidden.Name = wsNameHidden
End If
wsHidden.Visible = xlSheetVeryHidden
On Error GoTo 0
' Setup visible worksheet (Search Interface)
With wsVisible
.Cells.Clear
.Cells(1, 1).Value = "Enter Search Term(s):"
.Cells(1, 1).Font.Bold = True
.Cells(1, 2).Value = "Search"
.Cells(1, 2).Font.Bold = True
.Cells(1, 2).Interior.Color = RGB(173, 216, 230)
.Columns(1).ColumnWidth = 20
.Columns(2).ColumnWidth = 50
' Add search button
Dim btn As Object
Set btn = .Buttons.Add(300, 5, 100, 20)
btn.Caption = "Search"
btn.OnAction = "SearchKnowledgeBase"
End With
' Setup hidden worksheet (Knowledge Base)
With wsHidden
.Cells.Clear
.Cells(1, 1).Value = "Question"
.Cells(1, 2).Value = "Answer"
.Cells(1, 1).Font.Bold = True
.Cells(1, 2).Font.Bold = True
End With
End Sub
Sub SearchKnowledgeBase()
Dim wsVisible As Worksheet, wsHidden As Worksheet
Dim searchTerm As String, terms() As String, i As Long, j As Long, lastRow As Long
Dim output As String, term As String
' Define worksheet references
Set wsVisible = ThisWorkbook.Worksheets("SearchInterface")
Set wsHidden = ThisWorkbook.Worksheets("KnowledgeBase")
' Get the search term(s)
searchTerm = wsVisible.Cells(2, 2).Value
If searchTerm = "" Then
MsgBox "Please enter a search term.", vbExclamation
Exit Sub
End If
' Split the search terms into an array
terms = Split(searchTerm, " ")
' Search the knowledge base
lastRow = wsHidden.Cells(wsHidden.Rows.Count, 1).End(xlUp).Row
output = ""
For i = 2 To lastRow
For j = LBound(terms) To UBound(terms)
term = Trim(terms(j))
If term <> "" And _
(InStr(1, wsHidden.Cells(i, 1).Value, term, vbTextCompare) > 0 Or _
InStr(1, wsHidden.Cells(i, 2).Value, term, vbTextCompare) > 0) Then
output = output & "Question: " & wsHidden.Cells(i, 1).Value & vbCrLf & vbCrLf & _
"Answer: " & wsHidden.Cells(i, 2).Value & vbCrLf & "-----------------------" & vbCrLf & vbCrLf & vbCrLf
Exit For
End If
Next j
Next i
' Display results
If output = "" Then
MsgBox "No results found for the entered terms.", vbInformation
Else
MsgBox "Search Results:" & vbCrLf & vbCrLf & output, vbInformation
End If
End Sub