我正在处理需要在excel中使用嵌套公式的问题。例如:
我有一个错误列和一个用于分析的列
Error Analysis
Enter a valid material number Invalid Material
例如错误:
我在下一张表中有这样的错误和分析的汇编,我正在使用VLOOKUP与FIND一起查找已知错误的分析。
=VLOOKUP(LEFT(F2, FIND(" ", F2, FIND(" ", F2) + 1) - 1)&"*", 'Sheet2'!A:B, 2, 0)
我在这里要做的是从错误中提取前两个单词并在其中添加*并在VLOOKUP中使用它。
在另一张表中,它会像Vlookup“PO number *”,并获得它的分析。星号是因为我每天都得不到相同的号码。而且我也知道提取的错误的前两个单词将是唯一的。 (我知道“输入一个”作为前两个单词的错误不会再出现。)
现在我在同一列中出现错误,所以我想创建一个按钮并编写一个使用上述公式的代码。
我试图修改网上的一些代码,但我没有随处可见。我对VBA完全不熟悉。如果你能为此提供一个片段,那就太棒了。我会尝试复制程序以满足其他需求。
此代码似乎现在正在使用
Sub PopulateAnalysis()
Dim an_row As Long
Dim an_clm As Long
Dim lft As String
Dim st_num As Integer
Dim fin As String
Dim searchStr As String
Dim soughtStr As String
Table1 = Sheet1.Range("F2:F6") 'ErrorColumn from Error table (How do I make the range dynamic??)
Table2 = Sheet5.Range("A1:B6")
an_row = Sheet1.Range("G2").Row ' Populate this column from the analysis table on sheet2
an_clm = Sheet1.Range("G2").Column
For Each cl In Table1
'How do I translate the above formula into VBA statements??
st_num = InStr(InStr(cl, " ") + 1, cl, " ")
lft = left(cl, st_num - 1)
fin = lft & "*"
Sheet1.Cells(an_row, an_clm) = Application.WorksheetFunction.VLookup(fin, Table2, 2, True)
an_row = an_row + 1
Next cl
MsgBox "Done"
End Sub
答案 0 :(得分:0)
这应该有效。当然,您不需要调试行;)
Sub PopulateAnalysis()
Dim rngTableWithErrors As Range
Dim rngTableWithAnalysis As Range
Application.ScreenUpdating = False
'set the range for Table with error, Table1 on sheet 1
With Sheets(1) 'change to name of the sheet, more reliable than index num.
Set rngTableWithErrors = .Range("F2:F" & .Cells(.Rows.Count, 6).End(xlUp).Row)
Debug.Print rngTableWithErrors.Address
End With
'set the range for Table with Analysis, Table 2 on sheet 2
With Sheets(2) 'change to name of the sheet, more reliable than index num.
Set rngTableWithAnalysis = .Range("A1:B" & .Cells(.Rows.Count, 2).End(xlUp).Row)
Debug.Print rngTableWithAnalysis.Address
End With
'formula for cell G2
'=VLOOKUP(LEFT(F2;FIND(" ";F2;FIND(" ";F2)+1)- 1)&"*";Sheet2!A1:B23;2; 0)
rngTableWithErrors.Offset(0, 1).FormulaR1C1 = _
"=VLOOKUP(LEFT(R[0]C[-1],FIND("" "",R[0]C[-1],FIND("" "",R[0]C[-1])+1)-1)& ""*"",Sheet2!R1C1:R" & rngTableWithAnalysis.Rows.Count & "C2,2, 0)"
Application.ScreenUpdating = True
MsgBox "Done"
End Sub
您可以注意到,我们手动设置范围的左上角单元格。以某种方式找到左上角的单元格(使用Find method
是我最喜欢的)并从那里开始工作是一种更好的做法。你永远不知道,用户将如何更改工作表 - 即添加新的行,列等。