我遇到了VBA中的一些逻辑问题,根据我的经验,我发现这个问题非常棘手,我将尝试在下面解释。
我的工作表中有4列,结构如下
| A | | B | | C | | D |
|First Name| |Last Name| |Type| |Text|
我正在寻找一些可以有效扫描名字列的VBA,一旦遇到空白,就会启动以下逻辑
- 查看类型(C)列
- 如果遇到日记类型列中的文字,请检查位于文字(D)列中同一行的单元格
- 获取文本列中的自由文本,将其放入数组中。
- 使用数组中的文字并扫描名字列以查找匹配的文字条目,如果找到匹配项,则选择文字列中的匹配文字并粘贴它进入名字列。这样做直到阵列耗尽。
- 重新启动姓氏列
的第4步- 循环回到第1步
醇>注意:文本列中的文本是第三方应用程序(SAP)的自由文本摘录,因此我假设它包含名字或姓氏,它可以与已经位于名字和姓氏列中的条目相匹配
我一直在寻找可以有效地做到这一点的语法,但我仍然坚持为此编写逻辑并需要社区的一些建议,任何想法?
更新: 数据的一个例子就像这样
| A | | B | | C | | D |
| First Name | | Last Name | | Type | | Text |
| Michael | | Jackson | | WE | | SAP CATS |
| | | | | SS | | CATS O/H Michael Jackson|
答案 0 :(得分:2)
不确定你为什么要这样做,但这里是实现你所描述的逻辑的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
答案 1 :(得分:0)
我不认为我真的理解文本专栏,而且我并不是真正使用真正的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