首页 > 解决方案 > 为什么这个使用范围的类别搜索例程什么都不输出?

问题描述

这是我的第一个 excel VBA 程序。其目的是在列中搜索特定字符串,在本例中为“Popular Journalism”。如果找到该字符串,它将整个相应的行添加到结果范围。在搜索结束时,结果范围被复制到现有的空白工作表中。

它编译并运行没有问题。但是,尽管我在“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

标签: vbaexcel

解决方案


推荐阅读