为什么使用范围的此类别搜索例程什么都不输出?

时间:2018-08-22 14:47:22

标签: excel vba excel-vba

这是我的第一个excel VBA程序。其目的是在一列中搜索特定的字符串,在这种情况下为“大众新闻”。如果找到字符串,则将整个对应行添加到结果范围。搜索结束时,结果范围将复制到现有的空白工作表中。

它编译并运行没有问题。但是,尽管我已经使用“ C”列中的正确字符串创建了一个测试数据库,但搜索始终会返回空白的结果页面。

我在这段代码中误解了VBA的哪个方面?

来源:

Sub search_popularjournalism()

'Clear the previous results from the 'Results' worksheet
Worksheets("Results").UsedRange.ClearContents

'Variable Declarations
Dim cell As Variant 'Search FOR loop will iterate through each cell
Dim all_data As Range 'All data in database exluding unused cells
Dim category As Range 'This range is only the column containing categories
Dim results As Range 'The results of the category search
Dim row As Integer 'This counter will tell which row of data to add to results
Dim row_pull As Range 'This is the row to be added to results, conforms with Set protocol

'Initialize Variables and pull data into array
row = 1
Set results = Worksheets("Results").Range("A1")
Set all_data = Worksheets("Database").UsedRange
Set category = all_data.Columns("C")

'This for loop goes through each row of the 'Category' column.
'If the 'Category' column contains the correct category, the entire row
'is placed in the results range.
For Each cell In category
    If cell.Text = "Popular Journalism" Then
        row_pull = Rows(row).Cells
        results = Union(results, row_pull)
    End If
    row = row + 1
Next cell

'This line copies the entire results range into the 'Results' Worksheet
results.Copy Worksheets("Results").Range("A1")

MsgBox "Search Routine Complete"

End Sub

0 个答案:

没有答案