Excel VBA – 棘手索引逻辑到VBA

我遇到了VBA中的一些逻辑问题,我发现在我的经验中非常棘手,我将在下面进行解释。

我在工作表中有4列,结构如下

| A | | B | | C | | D | |First Name| |Last Name| |Type| |Text| 

我正在寻找一些可以有效扫描名字列的VBA,一旦遇到空白,就会启动下面的逻辑

  1. 查看Type(C)列
  2. 如果在“ 日记 ”types列中遇到文本,请检查文本(D)列中位于同一行的单元格
  3. 文本列中的自由文本放入数组中。
  4. 使用数组中的文本并扫描名字列以匹配文本条目,如果发现匹配,则将文本列中的匹配文本粘贴到“ 名字”列中。 直到数组用完为止。
  5. 重新启动“ 姓氏”列的第4步
  6. 循环回到步骤1

注意:“文本”列中的文本是来自第三方应用程序(SAP)的自由文本摘录,因此我假设它包含名或姓,可以将其与已经位于名字姓氏

我一直在寻找可以有效执行此操作的语法,但是我一直在为此编写逻辑,需要来自社区的一些build议,任何想法?

更新:数据的一个例子会是这样的

 | A | | B | | C | | D | | First Name | | Last Name | | Type | | Text | | Michael | | Jackson | | WE | | SAP CATS | | | | | | SS | | CATS O/H Michael Jackson| 

不太确定你为什么要这样做,但这里是vba,它实现了你所描述的逻辑:

 Sub t() For i = 2 To Range("A50000").End(xlUp).Row '1. Look in the Type (C) Column typ = Range("C" & i).Value '2. If it encounters text in the type column that says Journal then... If typ = "Journal" Then '...check the cell located in the same row in the Text (D) column txt = Range("D" & i).Value '3. Take the free text in the text column, put it into an array. txtArray = Split(txt, " ") '4. Use the text in the array and scan the First Name column for matching 'text entries, if it finds a match then take the matching text in the 'Text column and paste it into the First Name column. Do this until the 'array runs out. For Each t In txtArray For j = 2 To Range("A50000").End(xlUp).Row If Range("A" & j).Value = t Then match_txt = Range("D" & j).Value Range("A" & i).Value = match_txt End If Next j Next t '5. Restart step 4 for the Last Name column 'note: i would just do this in the above loop. 'split out here so that you can see step 5 seperately from step 4 For Each t In txtArray For j = 2 To Range("A50000").End(xlUp).Row If Range("B" & j).Value = t Then match_txt = Range("D" & j).Value Range("B" & i).Value = match_txt End If Next j Next t End If '6. loop back to step 1 Next i End Sub 

我不认为我真的理解了文本列,而且我并不是真正使用Excel的计算机(Mac Excel很糟糕),但是离开了我的头顶,我会这样做。

 Dim wSheet1 as Worksheet Sub main() Dim i As Long Set wSheet1 = Sheets(wSheet1) For i = 2 To getLastUsedRow(wSheet1) # Requirements #1 and #2 If wSheet1.Cells(i, "A") = "" And wSheet1.Cells(i, "C") = "Journal" Then processText(i, wSheet1.Range("A:A")) End If # Requirement #5 If wSheet1.Cells(i, "B") = "" And wSheet1.Cells(i, "C") = "Journal" Then processText(i, wSheet1.Range("B:B")) End If Next i End Sub Sub processText(i as Long, searchCol As Range) Dim words as Variant text = wSheet1.Cells(i, "D") # Requirement #3 words = Split(text, " ") For j = 0 To UBound(words) word = words(i) vTest = Application.VLookup(word, searchCol, 1, False) If IsError(vTest) = False Then # Requirement #4 wSheet1.Cells(i, "A") = word End If Next j End Sub Function getLastUsedRow(w as Worksheet) getLastUsedRow = w.UsedRange.Rows.Count End Function