Excel从A列循环并查找匹配值并将它们移动到新的工作表中。
对VBA来说,这是很新的。与A列中的药物相比,创建用于查找与工作表中相应值相匹配的药物名称的循环有困难。与A列的匹配将按顺序在第二工作表上报告。
意图:
原始数据-药物(A栏)与相应的数值(在B栏中)从一个细胞系列出。然后在C和D栏中分别列出另一细胞系的药物和相应值。这种情况可以持续下去,取决于检测了多少细胞株。关键是不是所有的细胞系都用同样的药物治疗。我们只对匹配的药物进行相应的排序。然后我们将能够比较药物在细胞中的作用。
有关数据集的示例,请参见所包含的图。细胞系(第1行)和药物与得分(第2行)的标题占据前2行。
从A列的第一种药物开始,Range (“A3”)在我的例子中,你会从C,E,G等列的匹配中看到,这取决于分析了多少细胞系。如果找到匹配的药物,则将药物及其相应的数据放在“排序”工作表上。例如,如果报告了3个有数据的细胞系,则将A细胞的原始药物名称和数据放在范围内(“A3,B3”),B细胞系的匹配将放在原状范围内(“C3,D3”),而来自细胞系3的匹配将放在范围内(“E3,F3”)。
我们有许多细胞株的药物和反应(分数)数据,但并不是所有的药物都在每个细胞系中被测试。我们想要找到在所有细胞系中测试过的普通药物。
我能够编写一个宏(见下文),以便在第一个比较列(C)中找到匹配项,并报告行值,但之后,当我试图考虑如何提取该名称和相应的值并将其移动到排序的工作表时,我陷入了困境。我知道复制、粘贴、偏移、循环的所有通用语言,但当我开始使用Dim的语言时,我就不知道如何提取这些发现了。
任何帮助都将不胜感激。提前感谢!
Sub Find_matching_drug()
'Declaring variables. will start with first _
drug in column A3, then move to A4, A5, etc _
matches with corresponding values will be sent _
to a different worksheet
Dim i As Integer, drug_to_find As String
'drug_to_find (variable) is defined as A3
drug_to_find = Range("A3").Value
MsgBox drug_to_find
For i = 1 To 500 ' searches column up to 500 rows for the match
If Cells(i, 3).Value = drug_to_find Then
MsgBox ("Found value on row " & i)
Exit Sub
End If
Next i
' This MsgBox will only show if the loop completes with no success
MsgBox ("Value not found in the range!")
End Sub发布于 2016-12-06 02:45:57
如果我的理解(见注释)是正确的,下面的代码应该(希望如此)?也许吧?)工作:
Sub Q40986052()
Dim src As Worksheet
Dim dst As Worksheet
Dim c As Long
Dim dstrow As Long
Dim numcols As Long
Set src = Worksheets("Sheet1")
Set dst = Worksheets("Sheet2")
'copy headings
numcols = src.Cells(2, src.Columns.Count).End(xlToLeft).Column
src.Range(src.Cells(1, 1), src.Cells(2, numcols)).Copy dst.Range("B1")
'create a list of all drugs
dstrow = 3
For c = 1 To numcols Step 2
src.Range(src.Cells(3, c), src.Cells(src.Rows.Count, c).End(xlUp)).Copy dst.Cells(dstrow, 1)
dstrow = dst.Cells(dst.Rows.Count, 1).End(xlUp).Row + 1
Next
'remove duplicate entries
dst.Range(dst.Cells(3, 1), dst.Cells(dstrow - 1, 1)).RemoveDuplicates Columns:=1, Header:=xlNo
dstrow = dst.Cells(dst.Rows.Count, 1).End(xlUp).Row + 1
'create vlookups
For c = 1 To numcols Step 2
dst.Range(dst.Cells(3, c + 1), dst.Cells(dstrow, c + 1)).FormulaR1C1 = "=IFERROR(VLOOKUP(RC1,'" & src.Name & "'!C[-1]:C,1,FALSE),"""")"
dst.Range(dst.Cells(3, c + 2), dst.Cells(dstrow, c + 2)).FormulaR1C1 = "=IFERROR(VLOOKUP(RC1,'" & src.Name & "'!C[-2]:C[-1],2,FALSE),"""")"
Next
'Calculate
dst.Calculate
'Convert to values
dst.Range(dst.Cells(3, 2), dst.Cells(dstrow, numcols + 1)).Value = dst.Range(dst.Cells(3, 2), dst.Cells(dstrow, numcols + 1)).Value
'remove temporary column
dst.Cells(1, 1).EntireColumn.Delete
End Subhttps://stackoverflow.com/questions/40986052
复制相似问题