【发布时间】:2021-06-02 09:56:59
【问题描述】:
背景资料:
我正在尝试在 Table 列中查找一个值并让它返回该表的行号。
表名为“Type_K”,在“DATA”表上,如下所示:
从用户输入中,我想在第二列中找到相同的值,然后返回表格行。这将用于“管道成本计算”表。 这是用户填写的表格: Material 列有一个包含 4 个选项的下拉列表,根据输入,Type 列会更改其下拉列表,Wall 和 Size 列也是如此。
对于这个例子,用户选择了:
材料 = 铜
类型 = 类型 K
墙(在这种情况下不适用)
尺寸 = 1/4"
Size 列的值是我想在 DATA 表中找到的值(第一张图像的第二列)
目前代码检查类型是什么并返回正确的表名
If Worksheets("Pipe Costing").Range("D" & ThisRow).Value = "Type K" Then
Copper_Type_ref = "Type_K"
ElseIf Worksheets("Pipe Costing").Range("D" & ThisRow).Value = "Type L" Then
Copper_Type_ref = "Type_L"
ElseIf Worksheets("Pipe Costing").Range("D" & ThisRow).Value = "Type M" Then
Copper_Type_ref = "Type_M"
ElseIf Worksheets("Pipe Costing").Range("D" & ThisRow).Value = "Type DWV" Then
Copper_Type_ref = "Type_DWV"
End If
“ThisRow”只是用户输入的行号(即他们正在更改第 4 行中的某些内容,因此 ThisRow=4)。
完整代码为:
Private Sub Copper_Data_Fill(ThisRow)
Dim Copper_Type_ref As String
Dim RowNum As Long
If Worksheets("Pipe Costing").Range("D" & ThisRow).Value = "Type K" Then
Copper_Type_ref = "Type_K"
ElseIf Worksheets("Pipe Costing").Range("D" & ThisRow).Value = "Type L" Then
Copper_Type_ref = "Type_L"
ElseIf Worksheets("Pipe Costing").Range("D" & ThisRow).Value = "Type M" Then
Copper_Type_ref = "Type_M"
ElseIf Worksheets("Pipe Costing").Range("D" & ThisRow).Value = "Type DWV" Then
Copper_Type_ref = "Type_DWV"
End If
'RowNum = Application.Match("F" & ThisRow, Worksheets("DATA").ListObjects(Copper_Type_ref).ListColumns(2).DataBodyRange, False).Row
'RowNum = Worksheets("DATA").ListObjects(Copper_Type_ref).ListColumns(2).DataBodyRange.Find("F" & ThisRow, xlValues).Row
RowNum = Worksheets("DATA").ListObjects(Copper_Type_ref).ListColumn(2).DataBodyRange.Find("F" & ThisRow, xlValues).Index
Worksheets("Pipe Costing").Range("H" & ThisRow).Value = Worksheets("DATA").ListObjects(Copper_Type_ref).DataBodyRange(RowNum, 4).Value
End Sub
我希望 RowNum 是表格行号,然后用它来填充最后一行
Worksheets("Pipe Costing").Range("H" & ThisRow).Value = Worksheets("DATA").ListObjects(Copper_Type_ref).DataBodyRange(RowNum, 4).Value
感谢任何帮助!
【问题讨论】:
-
您是从事件处理程序中调用它吗?查看用户正在编辑的表格会很有用。
-
我添加了更多信息,希望可以清除它。
-
没有足够的信息,但你可以试试:
Dim RowNum As Variant:RowNum = Application.Match("F" & ThisRow, Worksheets("DATA").ListObjects(Copper_Type_ref).ListColumn(2).DataBodyRange, 0):If IsNumeric(RowNum) Then。你绝对应该使用更多的变量来避免这么长的行。 -
我会尝试使用更多的变量,我对 VBA 还是很陌生,谢谢
标签: excel vba listobject