在比较之前拆分单元格列值

时间:2014-02-20 11:29:17

标签: excel excel-vba vba

我有两个电子表格,vda.xlsx和main.xlsm。目前我正在比较:

中的值

main.xlsm列J

vda.xlsx列A

查看是否匹配。如果找到匹配项,则列中的值将以红色突出显示。

但是vda.xlsx列A中的数据格式已更改。

过去看起来像这样

1234

现在看起来像这样

测试\ 1234 最佳\ 1234 Jest \ 1234 - 它可能是任何东西......

Sp我需要用“\”拆分Test \ 1234并提取1234进行比较。

知道我怎么能做到这一点。到目前为止,这是我的代码:

Sub VDA_Update()

Dim wshT As Worksheet
    Dim wbk As Workbook
    Dim wshS As Worksheet
    Dim r As Long
    Dim m As Long
    Dim cel As Range
    Application.ScreenUpdating = False
    Set wshT = ThisWorkbook.Worksheets("Master")
    On Error Resume Next

    ' Check whether vda.xlsx is already open
    Set wbk = Workbooks("vda.xlsx")
        On Error GoTo 0
        If wbk Is Nothing Then
        ' If not, open it
        Set wbk = Workbooks.Open("C:\Working\vda_test.xlsx")
    End If

    ' Set worksheet on vda.xlsx
    Set wshS = wbk.Worksheets("imac01")
    m = wshT.Cells(wshT.Rows.Count, 1).End(xlUp).Row

    ' Loop though cells in column J on main.xlsm
    For r = 1 To m
        ' Can we find the value in column C of vda.xlsx?

        Set cel = wshS.Columns(1).Find(What:=wshT.Cells(r, 10).Value, _
            LookAt:=xlWhole, MatchCase:=False)

        If Not cel Is Nothing Then

            ' If we find a match, then change the text to red
            wshT.Cells(r, 10).Font.ColorIndex = 3

        End If
    Next r

    Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:1)

使用Split(CellValue, "\")获取数组,然后检索数组中的最后一项。

变化:

' Loop though cells in column J on main.xlsm
For r = 1 To m
    ' Can we find the value in column C of vda.xlsx?

    Set cel = wshS.Columns(1).Find(What:=wshT.Cells(r, 10).Value, _
        LookAt:=xlWhole, MatchCase:=False)

    If Not cel Is Nothing Then

        ' If we find a match, then change the text to red
        wshT.Cells(r, 10).Font.ColorIndex = 3

    End If
Next r

类似于:

' Loop though cells in column A on vda.xlsx
For r = 1 To m
    ' Can we find the value in column J of main.xlsm?

    cellSplit = Split(wshS.Cells(r, 1).Value, "\")
    Set cel = wshT.Columns(10).Find(cellSplit(UBound(cellSplit)), _
        LookAt:=xlWhole, MatchCase:=False)

    If Not cel Is Nothing Then

        ' If we find a match, then change the text to red
        cel.Cells(1, 1).Font.ColorIndex = 3

    End If
Next r
相关问题