Excel如何使用InStr

时间:2016-10-12 12:54:54

标签: excel if-statement

If InStr(1, UCase(CStr(compare_DU_ID)), "L4L", 1) >= 1 Then
    If UCase(CStr(compare_DU_ID)) = UCase(CStr(DU_ID)) Then 'If L4L in compare_DU_ID, then DU_ID definitely equals to compare_DU_ID
        Worksheets("Sheet2").Cells(y, 97).Value = Updated_Date '1. Cells(y, 97) might need to change, depending on which contract date you want to update
    End If
ElseIf InStr(1, CStr(compare_DU_ID), CStr(DU_ID), 1) = 1 Then
    Worksheets("Sheet2").Cells(y, 97).Value = Updated_Date
ElseIf InStr(1, CStr(DU_ID), CStr(compare_DU_ID), 1) = 1 Then
    Worksheets("Sheet2").Cells(y, 97).Value = Updated_Date
End If

我有更新日期的问题。例如,第一种情况,如果CStr(DU_ID) = 1731WGCStr(compare_DU_ID) = 31731WG,那么日期将不会更新。第二种情况,当CStr(DU_ID) = 1392WGCStr(compare_DU_ID) = 11392WG时,日期将会更新。

我需要调整哪些代码,以便第二种情况也不会改变。

另外,我认真地认为11392WG会更新是因为它以“1”开头,所以是1392WG。并且31731WG不会被更改是因为它不以“1”开头,这是1731WG的第一个值。

1 个答案:

答案 0 :(得分:0)

您正在使用此版本的功能

Public Shared Function InStr(_
  ByVal Start As Integer, _
  ByVal String1 As String, _
  ByVal String2 As String, _
  Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod _
) As Integer

哪个没问题,请注意你可以在函数VbCompareMethod.vbTextCompare的末尾代替1,或者根本不说。

我认为问题是你希望它是1而不是> = 1.

If InStr(1, UCase(CStr(compare_DU_ID)), "L4L", 1) >= 1 Then
   If UCase(CStr(compare_DU_ID)) = UCase(CStr(DU_ID)) Then 'If L4L in compare_DU_ID, then DU_ID definitely equals to compare_DU_ID
         Worksheets("Sheet2").Cells(y, 97).Value = Updated_Date '1. Cells(y, 97) might need to change, depending on which contract date you want to update
   End If
ElseIf InStr(1, CStr(compare_DU_ID), CStr(DU_ID), 1) < 1 Then
   Worksheets("Sheet2").Cells(y, 97).Value = Updated_Date
ElseIf InStr(1, CStr(DU_ID), CStr(compare_DU_ID), 1) < 1 Then
   Worksheets("Sheet2").Cells(y, 97).Value = Updated_Date
End If  

试试这个,请注意,我已经在第4行和第6行更改了缩进和=1>=1