定义数组search的术语

我一直在寻找答案,但是我一直没有find足够的东西来填补我的VBA知识的空白。

我将两个数据列表放到数组中,使用这里find的代码的修改版本进行比较(我将在下面发布)。

但是,我不想将整个单元格input到数组中,以便与第二个数组进行比较。 例如,如果第一个表格中的单元格显示“Company,LLC”,我只想search“Company”。 我有一些代码,这样做:

s = rCell.Value indexofthey = InStr(1, s, ",") aftercomma = Right(s, Len(s) - indexofthey + 1) celld = Left(s, Len(s) - Len(aftercomma)) 

我需要以某种方式工作的代码(从上面链接的问题的答案复制)是这样的:

  Option Explicit Private Sub cmdCompare2to1_Click() Dim sheet1 As Worksheet, sheet2 As Worksheet, sheet3 As Worksheet Dim lngLastR As Long, lngCnt As Long Dim var1 As Variant, var2 As Variant, x Dim rng1 As Range, rng2 As Range Set sheet1 = Worksheets(1) Set sheet2 = Worksheets(2) Set sheet3 = Worksheets(3) ' assumes sheet3 is a blank sheet in your workbook Application.ScreenUpdating = False 'let's get everything all set up 'sheet3 column headers sheet3.Range("A1:B1").Value = Array("in1Not2", "in2Not1") 'sheet1 range and fill array With sheet1 lngLastR = .Range("A" & .Rows.Count).End(xlUp).Row Set rng1 = .Range("A1:A" & lngLastR) var1 = rng1 End With 'sheet2 range and fill array With sheet2 lngLastR = .Range("A" & .Rows.Count).End(xlUp).Row Set rng2 = .Range("A1:A" & lngLastR) var2 = rng2 End With 'first check sheet1 against sheet2 On Error GoTo NoMatch1 For lngCnt = 1 To UBound(var1) x = Application.WorksheetFunction.Match(var1(lngCnt, 1), rng2, False) Next 'now check sheet2 against sheet1 On Error GoTo NoMatch2 For lngCnt = 1 To UBound(var2) x = Application.WorksheetFunction.Match(var2(lngCnt, 1), rng1, False) Next On Error GoTo 0 Application.ScreenUpdating = True Exit Sub NoMatch1: sheet3.Range("A" & sheet3.Rows.Count).End(xlUp).Offset(1) = var1(lngCnt, 1) Resume Next NoMatch2: sheet3.Range("B" & sheet3.Rows.Count).End(xlUp).Offset(1) = var2(lngCnt, 1) Resume Next End Sub 

假设您不想更改单元格中的值,则需要循环访问数组。 你可以像这样使用一个proc:

 Sub RemoveUnwantedText(ByRef theArray As Variant) Dim theValue As String Dim i As Long Dim indexOfComma As Integer ' array is created from single-column range of cells ' and so has 2 dimensions For i = LBound(theArray, 1) To UBound(theArray, 1) theValue = CStr(theArray(i, 1)) indexOfComma = InStr(1, theValue, ",") If indexOfComma > 0 Then theValue = Trim(Left(theValue, indexOfComma - 1)) End If theArray(i, 1) = theValue Next i End Sub 

将其粘贴到与您的代码相同的模块中。 在你的代码中,在做任何比较之前,添加这些调用:

 RemoveUnwantedText var1 RemoveUnwantedText var2