选择表格中的前N%数据

时间:2016-04-25 13:46:56

标签: excel vba excel-vba

我正在处理一个userform,我从sql server中的表中提取数据,我提取了前80%的数据并将其放在带有vba代码的excel文件中。 我想要做的是从excel表中保存的80%数据我希望允许用户通过输入文本区域中的数字从excel表中选择一定百分比的数据是否可以这样做?

这是我用来从sql server从数据库中提取的代码:

Private Sub CommandButton1_Click()

Dim sSql As String
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Dim cmdObj As ADODB.Command
Dim qf As Object

Sheets("sheet1").Select
Selection.ClearContents

Set cn = New ADODB.Connection
cn.Open "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=swat_admin;PASSWORD=swat_admin;Initial Catalog=SWAT_V2_PLL;Data Source=NCEFORREP"
sSql = "select TOP 80 PERCENT func.coresitecode,func.SiteCode,feature_id, TOTAL_PNRs,PNR_rank_id from rpt.functional_site_mapping func inner join  (select TOP 80 PERCENT * from  rpt.top_PNR_contributing_sites order by TOTAL_PNRs DESC) PNR on func.ptf_id = pnr.ptf_id and func.coresitecode = pnr.coresitecode and func.sitecode = pnr.sitecode order by PNR_rank_id  "
Set rs = New ADODB.Recordset
rs.CursorLocation = adUseClient
rs.Open sSql, cn, adOpenForwardOnly, adLockReadOnly, adCmdText

If rs.EOF Then
MsgBox (" the record set is empty. rs.EOF = " & rs.EOF)
Else
MsgBox ("The number of rows returned from the query is:  " & rs.RecordCount)
Range("a1").Select
For Each qf In rs.Fields
  Range("a1").Offset(0, coloffset).Value = qf.Name
  coloffset = coloffset + 1
Next qf

Range("a2").CopyFromRecordset rs
rs.Close
Set rs = Nothing

End If
End sub 

这是我的excel文件,如果有人可以帮助我,谢谢你:

http://www.cjoint.com/c/FDzjyTNB1Lv

1 个答案:

答案 0 :(得分:0)

确保获得vb变量中的百分比,例如myPercent, *然后检查它是0到100之间的数字 *然后在现有查询中使用它

所以

sSql = "select TOP 80 PERCENT 

变为

sSql = "select TOP " & myPercent & "PERCENT 

希望有所帮助