How to modify this script to account for different case?

杀马特。学长 韩版系。学妹 提交于 2019-12-11 09:56:54

问题


I wrote a VBA script which searches for a string in one column and returns the match in another column. The point is match an item number to it's product image by SKU. The problem is that it fails if the case of the item number and the image have different case. The script is below:

Sub Test()
    Dim NA As Long, NC As Long, v As String, I As Long, J As Long
    Dim v2 As String
    NA = Cells(Rows.Count, "A").End(xlUp).Row
    NC = Cells(Rows.Count, "C").End(xlUp).Row
    For I = 2 To NA
        v = Cells(I, "A").Value
        v2 = ""
        For J = 2 To NC
            If InStr(Cells(J, "C").Value, v) > 0 Then
                v2 = v2 & ";" & Cells(J, "C").Value
            End If
        Next J
        Cells(I, "A").Offset(0, 1).Value = Mid(v2,2)
    Next I
End Sub

How can I account for different case? Is there a method for this?


回答1:


Pretty simple, just cast it to lower case:

Sub Test()
    Dim NA As Long, NC As Long, v As String, I As Long, J As Long
    Dim v2 As String
    NA = Cells(Rows.Count, "A").End(xlUp).Row
    NC = Cells(Rows.Count, "C").End(xlUp).Row
    For I = 2 To NA
        v = LCase(Cells(I, "A").Value)
        v2 = ""
        For J = 2 To NC
            If InStr(LCase(Cells(J, "C").Value), v) > 0 Then
                v2 = v2 & ";" & Cells(J, "C").Value
            End If
        Next J
        Cells(I, "A").Offset(0, 1).Value = Mid(v2,2)
    Next I
End Sub

I just took your code sample and put casts to lower case on v and Cells(J, "C").Value.

I didn't test this, so I can't guarantee flawless functionality.


You can also alter your module (on top) with

Option Compare Text

That will shut down case sensitivity completely (so you wouldn't need LCase(..))




回答2:


Just use the vbTextCompare option of the Instr function.

If InStr(1, Cells(J, "C").Value, v, vbTextCompare) > 0 Then
    v2 = v2 & ";" & Cells(J, "C").Value
End If

[vbTextCompare] Performs a text comparison, based on a case-insensitive text sort order determined by your application's current culture information.



来源:https://stackoverflow.com/questions/28302691/how-to-modify-this-script-to-account-for-different-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!