以我之前发布的一个StackOverflow问题为基础:Indexing by ROW on a Column and finding partial matches in a string
我正在为此创建一个变体,但字符串匹配-例如复制整个行(A1:C1),然后在新工作表的下一个空行位置插入。
Sub PeopleFilter()
' Defining Workbook and Worksheets to be used
Dim PeopleWorkbook As Workbook
Dim People As Worksheet
Dim UnitedKingdom, UnitedStates, Canada As Worksheet
' Letting our Variables equal something
Set PeopleWorkbook = ActiveWorkbook
Set People = PeopleWorkbook.Worksheets("People")
Set UnitedKingdom = PeopleWorkbook.Worksheets("United Kingdom")
Set UnitedStates = PeopleWorkbook.Worksheets("United States")
Set Canada = PeopleWorkbook.Worksheets("Canada")
' Defining ranges
Dim PeopleDataRange As Range
' C1 is cell 1 - C2, cell 2
Dim C1 As Range
Dim C2 As Range
' Equating C1 to the cell that is at the 2nd row first column
' Equating C2 to the cell that is at the last row position first column
Set C1 = People.Cells(2, 1)
Set C2 = People.Cells(People.UsedRange.Rows.Count, 1)
' Creating a range out of these two cells
Set PeopleDataRange = People.Range(C1, C2)
' Printing length of Range
Debug.Print PeopleDataRange.Count
' For each row
Dim ThisWorks As Boolean
For Each c In PeopleDataRange.Rows
If People.Rows(c, 2).Value = "United States" Then
ThisWorks = True
Else
ThisWorks = False
End If
Next c
End Sub
我目前正在调试-这就是为什么除了更改布尔值外,它实际上不做任何事情。
出现错误如果People.Rows(c,2).Value =“美国”,则 错误代码:1004-应用程序或对象定义的错误
工作流程应如下-找到特定的字符串匹配项后,在整个列中建立索引-复制选定的列。
IE如果在第35行找到了匹配的字符串-将第35行的A,b,c,d ...列返回到新工作表。
*编辑-预期的结果应该是每次循环都迭代-值与查找匹配时,布尔值应该变为true
1:真 2:错误 3:真 4:假 5:假 6:错误*
答案 0 :(得分:1)
c
不是行号,而是包含A列中单元格的范围。您需要引用该行:
If People.cells(c.row, 2).Value = "United States" Then