我从2个表中提取数据,一个按预期工作。但另一个,同样的代码,不会工作。我就是不明白。一切似乎都是一样的。我把"find"隔离了出来。它们在两个表中返回正确的行号。
问题是loCustomerTable在.value中似乎没有任何东西调试。Print做换行,就是这样。没有错误生成。
为什么?我错过了什么?
Dim rProjectInfo As range
Dim rCustomerInfo As range
Dim loCustomerTable As ListObject
Dim loProjectTable As ListObject
Set loProjectTable = Worksheets("projektinformation").ListObjects("tblProjektinformation")
Set loCustomerTable = Worksheets("kundinfo").ListObjects("tblKundInformation")
sProjectNumber = "20-130"
' read project information
Set rProjectInfo = loProjectTable.range.rows((loProjectTable.range.Columns(1).Find(sProjectNumber).row))
' get customer info base off project info.
Set rCustomerInfo = loCustomerTable.range.rows((loCustomerTable.range.Columns(2).Find("gateau").row))
Debug.Print rProjectInfo.Cells(, 1).Value
Debug.Print rCustomerInfo.Cells(, 2).Value
我猜你是你的怪物语句的受害者(我不明白为什么这样的语句不被分成更小的部分,以便你可以轻松地调试它)。
那么我们拆分语句
Set rCustomerInfo = _
loCustomerTable.range.rows((loCustomerTable.range.Columns(2).Find("gateau").row))
首先获取表列
dim tabCol as Range
set tabCol = loCustomerTable.range.Columns(2)
Debug.Print tabCol.Address
检查地址是否正确(should by)。现在在该列
中搜索字符串("gateau")dim rGateau as Range, row as long
set rGateau = tabCol.Find("gateau")
row = rGateau.Row
Debug.Print rGateau.Address, rGateau.Value2, row
给出带有搜索字符串的单元格的地址(代码假定总能找到此字符串)及其行号。
现在您将看到的是,行号是工作表中的行,而不是表(listObject)中的行-但是您使用它作为表中的行号。如果表不是从第1行开始,那么您现在是从错误的行(甚至可能在表的下面)读取数据。您可以做的是考虑表的开头,或者将表与找到名称的行相交。
' Variant 1: Calculate the row number within the table
row = rGateau.Row - loCustomerTable.Range.Row + 1
Set rCustomerInfo = loCustomerTable.Range.Rows(row)
' Variant 2: Intersect the (sheet) row with the table
row = rGateau.Row
Set rCustomerInfo = Intersect(loCustomerTable.Parent.Rows(row), loCustomerTable.Range)
Debug.Print rCustomerInfo.address