1

我们正在尝试根据某些条件获取特定记录集的行号。考虑下表

Name    Id
abc     1
cde     2
efg     3

现在,如何获取员工“cde”的行号或记录集号(根据下面的代码,我们需要得到结果为 2)。请对此有任何帮助。

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001
strSource="C:\Test.xls"
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strSource          & ";Extended Properties=""Excel 8.0;HDR=Yes;"";"  
Set conn = CreateObject("ADODB.Connection")   
Set objRecordSet = CreateObject("ADODB.Recordset")
conn.Open strConnection 
objRecordset.Open "Select Name FROM [sheet1$] Where Id = 2", conn, adOpenStatic,     adLockOptimistic, adCmdText
msgbox objRecordset.GetString
conn.Close 
Set conn = Nothing
4

1 回答 1

1

最好的方法是在 Excel 文件中放置一个与行号具有相同数据的列。然后查询该列。这是一个万无一失的解决方案。

但是,如果由于某种原因你不能这样做,那么试试这个:

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Dim RowNumber 
Dim SqlStmt 

strSource = "C:\Temp\Test.xls"
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strSource & ";Extended Properties=""Excel 8.0;HDR=Yes;"";"
Set conn = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")
conn.Open strConnection

SqlStmt = "Select Name, Id FROM [sheet1$]"      ''-- you can optimize this query if your Id is in ascending order. e.g. "Select Name, Id FROM [sheet1$] Where Id <= 4"
objRecordset.Open SqlStmt, conn, adOpenStatic, adLockOptimistic, adCmdText
objRecordset.Find "Id = 4"
RowNumber = objRecordset!ID + 1  ''-- +1 for Header row.
conn.Close
Set conn = Nothing

MsgBox RowNumber
于 2013-04-18T16:09:45.890 回答