2017-04-04 40 views
1

我有数据表明它不在单元格中的一致位置,有时它有分号,有时位于分号的右侧或左侧。我期待的最终结果是在B列中列出所有“学生”(由不是教师定义)和列C中的所有教师。如果找不到学生或教师,则相应的单元格应为空白。VBA查找单元格中的字符串并将其复制到不同的单元格

目前我正在做一个文本列分隔两列然后用下面的公式来有学生和老师分开:

=IF(SUMPRODUCT(--ISNUMBER(SEARCH({"Arts and Music","Math and Science"},A2)))>0,B2,C2) 

=IF(SUMPRODUCT(--ISNUMBER(SEARCH("Teacher",A2)))>0,B2,C2) 

我还要做手工查找和替换删除括号和文本,只留下学生/教师的名字。

是否有任何VBA宏可以帮助我从列A获得预期的结果在列B和C?谢谢。

enter image description here

+3

是的,你写的。这不是一个代码写入服务。努力自己写一个问题,并问你是否遇到问题。三个实际上是几十个(如果不是数百个)关于循环遍历VBA中的单元格的现有问题,您可以使用它来开始。 –

回答

1

您可以使用正则表达式来做到这一点。请参阅post以了解如何在Excel中启用它们。

Sub FindStrAndCopy() 
Dim regEx As New RegExp 
regEx.Pattern = "\s*(\w+)\s*\((.+)\)" 

With Sheets(1): 
    Dim arr() As String 
    Dim val As String 

    Dim i As Integer, j As Integer 
    Dim person As String, teachOrSubject As String 
    Dim mat As Object 

    For i = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row: 
    val = Cells(i, "A").Value 
    arr = Split(val, ";") 
    For j = 0 To UBound(arr): 
     Set mat = regEx.Execute(arr(j)) 
     If mat.Count = 1 Then 
     person = mat(0).SubMatches(0) 
     teachOrSubject = mat(0).SubMatches(1) 
     If teachOrSubject = "Teacher" Then 
      Cells(i, "C").Value = person 
     Else 
      Cells(i, "B").Value = person 
     End If 
     End If 
    Next 
    Next 

End With 
End Sub 

宏将字符串拆分为分号,并将1或2个子字符串存储在'arr'数组中。然后它会在每个表达式上进行正则表达式。如果括号内的字符串是“老师”,则先前的人名将存储在“C”列中,否则它是学生,名称存储在列“B”中。

+0

我知道我不应该在评论中说谢谢,但这很好。我并不期待解决方案,但这完美地解决了我的问题。很高兴看到仍有人愿意为别人提供帮助并为此付出更多的努力。我总是尽力在我所能做到的地方做到这一点。再次感谢。 – chupeman

0

我创建了一个按钮,上面写着你对列的所有注册一个 再换上B列 学生然后把老师对C列

检查,我使用“(老师)”知道什么时候老师在字符串中 我使用了名为“Sheet1”的工作表 而我不使用第一行,因为是标题行。

如果您有任何问题,请与我联系。

Private Sub CommandButton1_Click() 
'---------------------------------Variables----------------------------- 
Dim total, i, j As Integer 
'--------------Counting the number of the register in column A---------- 
ThisWorkbook.Sheets("Sheet1").Range("XDM1").Formula = "=COUNTA(A:A)" 
total = CInt(ThisWorkbook.Sheets("Sheet1").Range("XDM1").Value) 
'---------------------Creating arrays to read the rows------------------ 
Dim rows(0 To 1000) As String 
Dim columnsA() As String 
'------------Searching into the rows to find teacher or student--------- 
For i = 2 To total 
    columnsA = Split(ThisWorkbook.Sheets("Sheet1").Range("A" & i).Value, ";") 
    first = LBound(columnsA) 
    last = UBound(columnsA) 
    lenghtOfArray = last - first 
    MsgBox lenghOfArray 
    For j = 0 To lenghtOfArray 
     If InStr(columnsA(j), "(Teacher)") > 0 Then 
      MsgBox columnsA(j) 
      ThisWorkbook.Sheets("Sheet1").Range("C" & i).Value = columnsA(j) 
     Else 
      ThisWorkbook.Sheets("Sheet1").Range("B" & i).Value = columnsA(j) 
     End If 
    Next j 
Next i 
'--------------------------------Finishing------------------------------ 
End Sub 
相关问题