2014-06-30 212 views
0

我试图设计一个函数,该函数搜索特定术语的第一行,然后在术语“Requirement”或“Function Change”中搜索该列。一旦找到这些术语,它将搜索包含这些术语的行,并在另一列中检查术语“协议”。我试图用Like操作符来完成这个任务,但我一直在弹出一个“应用程序定义或对象定义的错误”。任何人都可以弄清楚为什么我可能会得到这个错误?我一直在看它一段时间,无法弄清楚。下面的代码我到目前为止:在VBA中执行Like运算时出现运行时错误

编辑:错误时弹出的代码获取到第一IF语句

Function CountProtocol() As Long 

Sheets("CS-CRM Raw Data").Select 
Sheets("CS-CRM Raw Data").Unprotect 

    LastRow = Range("A" & Rows.Count).End(xlUp).row 
    LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column 

    For i = 1 To LastRow 
     If Cells(i, myTypeCol).Value Like "Functional Change" Or "Requirement" Then 
      If Cells(i, myDescCol).Value Like "*protocol*" Then 
       pro_count = pro_count + 1 
      End If 
     End If 
    Next i 

    MsgBox "Requests of type ""Requirement"" or ""Functional Change"" that have ""Protocol"" in the description: " & pro_count 

CountProtocol = Pro 

End Function 

编辑:这里是myTypeCol分配代码:

Function ColSearch(Heading As String) As Integer 

Sheets("CS-CRM Raw Data").Select 
Sheets("CS-CRM Raw Data").Unprotect 

myCol = Sheets("CS-CRM Raw Data").Cells.Find(What:=Heading, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False).Column 

ColSearch = myCol 

End Function 

这就是所谓的主子程序是这样的:

myTypeCol = ColSearch("type") 
myDescCol = ColSearch("description") 

编辑:这是另外一个功能我哈这是调用myTypeCol,可以正常工作,没有错误。

Function CountType() As Long 

Sheets("CS-CRM Raw Data").Select 
Sheets("CS-CRM Raw Data").Unprotect 

Dim type_count As Long 
Dim type_count2 As Long 
Dim type_sum As Long 

    LastRow = Range("A" & Rows.Count).End(xlUp).row 
    LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column 

    type_count = Application.WorksheetFunction.CountIf(Range(myTypeCol & "2:" & myTypeCol & LastRow), "Requirement") 
    type_count2 = Application.WorksheetFunction.CountIf(Range(myTypeCol & "2:" & myTypeCol & LastRow), "Functional Change") 

    type_sum = type_count + type_count2 

    MsgBox "Requests of type ""Requirement"" or ""Functional Change"": " & type_sum 

CountType = Count 

End Function 

回答

2

您需要Or操作后对单元格的值进行比较,像这样:

Function CountProtocol() As Long 

Sheets("CS-CRM Raw Data").Select 
Sheets("CS-CRM Raw Data").Unprotect 

    LastRow = Range("A" & Rows.Count).End(xlUp).row 
    LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column 

    For i = 1 To LastRow 
     If Cells(i, myTypeCol).Value Like "Functional Change" Or Cells(i, myTypeCol).Value Like "Requirement" Then 
      If Cells(i, myDescCol).Value Like "*protocol*" Then 
       pro_count = pro_count + 1 
      End If 
     End If 
    Next i 

    MsgBox "Requests of type ""Requirement"" or ""Functional Change"" that have ""Protocol"" in the description: " & pro_count 

CountProtocol = Pro 

End Function 
+0

啊,好赶上。尽管如此,我仍然无法正常工作。当我进行上述建议的编辑时,我会在“Sheets(”CS-CRM Raw Data“)中得到一个”下标超出范围错误“,选择”line。如果我评论Sheets线,我会再次得到原始错误。“ – user3783788

+0

@ user3783788在哪里分配了myTypeCol?如果它没有被分配(看起来不是),那么它的默认值是'0',这会引起1004的错误 –

+0

我有一个不同的函数, – user3783788