Get Row number of excel using ADO

别等时光非礼了梦想. 提交于 2019-12-24 09:26:41

问题


We are trying to get the row number of particular recordset retreived based on soome condtion. consider below table

Name    Id
abc     1
cde     2
efg     3

Now, how to get the row number or recordset number of employee "cde" (accrding to below code we need to get the result as 2). Any help on this please.

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

回答1:


The best way is to put a column in the Excel file that has the same data as the row number. Then query on that column. That is a fool-proof solution.

However, if for some reason you can't do that, then try this:

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


来源:https://stackoverflow.com/questions/16086758/get-row-number-of-excel-using-ado

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!