在excel公式中有一种方法而不是vba脚本来搜索列中的特定文本并从另一列的同一行返回结果。如果这不能在公式中完成,如何在VBA中完成?
示例:
(Column A) Hostname
UK-Aaron-01
UK-Bob-01
UK-AaronOoi
UK-XP-Peter
UK-XP-Jack
UK-Brandon
(Column B) Hostname Department
==This will be the place where the result would be
(Column C) User
Aaron
Acciai
Achilles
Acton
AaronOoi
Adarsh
Aba
Abbas
Bob
Abeeku
Abhay
Abner
Absolom
Peter
Acoose
Adagio
Brandon
(Column D) Department
Marketing
IT
Sales
HR
Marketing
IT
HR
arketing
Sales
HR
Marketing
IT
HR
Marketing
IT
Sales
The result in (Column B) should be:
Marketing
Marketing
IT,HR (If UK-AaronOoi match 2 names "Aaron" & "AaronOOi" then it will be separated with coma)
HR
NotFound (If no match then return not found)
Sales
主机名,用户&部门包含超过4k的数据
答案 0 :(得分:0)
Aaron,在VBA你可以做到这一点,但我已经将假设最小化,以使其更简单:
假设您只有原始A:
VBA代码将是这样的:
Sub find_department_by_name()
Dim i As Integer
For i = 1 To 3:
If Cells(i, 1).value Like "*-Aaron-*" Then
Cells(i, 2).value = "Marketing"
Else:
Cells(i, 2).value = "Not Found"
End If
Next
End Sub
当你运行它时,你将在B列中找到:
我希望这是你正在寻找的东西(当然你需要根据自己的需要定制它)
答案 1 :(得分:0)
我终于能够使用toufikovich和其他Google的简单指南来解决这个问题。这是我第一次做VBA脚本,如果它看起来像新手那么很难开始这样的借口:)
Private Sub Run()
Dim lastRowB As Integer
Dim lastRowC As Integer
Dim i As Integer
Dim k As Integer
With ActiveSheet
lastRowB = .Cells(.Rows.Count, "A").End(xlUp).Row 'Get Row last number in A with data
End With
With ActiveSheet
lastRowC = .Cells(.Rows.Count, "C").End(xlUp).Row 'Get Row last number in C with data
End With
For k = 2 To lastRowB: 'Run a loop for each hostname in Column B
For i = 2 To lastRowC: 'Run a lopp for each user in column C
If Cells(k, 1).Value Like "*" & Cells(i, 3).Value & "*" Then 'Check if Cell in A is like Cell in C with wildchard
Cells(k, 2).Value = Cells(k, 2).Value & "," & Cells(i, 4).Value 'Check if there is more than 1 similar User match saperate them by coma ","
If Left(Cells(k, 2).Value, 1) = "," Then ' If the string start with coma ","
Cells(k, 2).Value = Right(Cells(k, 2).Value, Len(Cells(k, 2).Value) - 1) ' Then remove the first text
End If
End If
Next
Next
End Sub
答案 2 :(得分:0)
最简单的方法是:
vlookup = vlookup("*desiredtextstring*",a1:a11,1,0)
或者,要返回展开的所需文字,可以将vlookup
替换为hlookup