excel查询数据

2025-10-04 13:19:14

1、创建带胡宏的excel

新建excel,单击左上角“office按纽”→“另存为”→“启用宏的excel工作薄(M)”;保存后,关闭当前excel,然后打开有“宏”的excel(另存为的excel)

附:有宏的excel工作薄,图标有个大大的感叹号

excel查询数据

excel查询数据

2、接下来要打开宏编辑器,两种方法任选

(1)单击“开发工具”菜单→“visual Basic”

(2)快捷键“alt+f11”

然后会弹出一个新的页面,所有的代码都在这个窗口进行编写

excel查询数据

3、然后引入相关库

在宏窗口中单击“工具”菜单→“引用”项,然后按下图选择要添加的库,“确定”完成操作

excel查询数据

1、在“sheet1”表格中,插入如下数据(如图),然后将“sheet1”表更名为“成绩表”(这个表名要在编码中用,如果是别的名称,只要改下代码即可)

excel查询数据

2、做完第一步切换到“sheet2”表中,按下图录入数据,并将“sheet2”表更名为“查询表”

excel查询数据

3、在“查询表(即sheet2)”中插入一个查询按钮

(1)单击“开发工具”菜单→“插入”→“activex控件”下的“命令按钮”;

(2)接下来鼠标的光标会变成一个小“十”字形状,这时你按住鼠标,往右下角方向拖动后就会画出一个新的命令按钮了;

(3)右键命令按钮→“命令按钮 对象”→“编辑”,可以更改按钮名称,这里更改为“查询”

(4)现在的的“查询”按钮,处在“设计模式”,我们要将它变成应用模式,点再次点击“设计模式”后,就可以了

excel查询数据

excel查询数据

excel查询数据

4、(1)进入宏编辑器,按“alt+f11”快捷键。

(2)双击左侧“sheet2(查询表)”,将如下代码粘贴至右侧

Private Sub CommandButton1_Click()

    Dim cnn As New ADODB.Connection

    Dim rs As New ADODB.Recordset

    Dim strsql As String

    

    ' --连接数据库

    cnn.Open "provider=Microsoft.Jet.Oledb.4.0;Extended Properties ='Excel 8.0';Data Source =" & ThisWorkbook.FullName

    

    ' --查询语句

    strsql = "select 班级, 姓名, 语文, 数学, 英语 from [成绩表$] Where 1=1 "

    If (Range("b1") <> "") Then strsql = strsql & "and 班级='" & Range("b1") & "'"

    If (Range("d1") <> "") Then strsql = strsql & "and 姓名='" & Range("d1") & "'"

    If (Range("f1") <> "") Then strsql = strsql & "and 语文>=" & Range("f1")

    If (Range("f2") <> "") Then strsql = strsql & "and 语文<=" & Range("f2")

    If (Range("h1") <> "") Then strsql = strsql & "and 数学>=" & Range("h1")

    If (Range("h2") <> "") Then strsql = strsql & "and 数学<=" & Range("h2")

    If (Range("j1") <> "") Then strsql = strsql & "and 英语>=" & Range("j1")

    If (Range("j2") <> "") Then strsql = strsql & "and 英语<=" & Range("j2")

       

    ' --执行语句

    Set rs = cnn.Execute(strsql)

    ' --清空表格范围

    Range("a5:j65536").ClearContents

    ' --查询结果显示起始位置

    Range("a5").CopyFromRecordset rs

    rs.Close

    Set rs = Nothing

    cnn.Close

    Set cnn = Nothing

End Sub

excel查询数据

excel查询数据

5、最后,验收成果的时刻到了

回到excel页面,输入查询条件,点击“查询”按钮。

搞定,收工

excel查询数据

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢