|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
ComboBox使用三种方法:为了能使用请用2007或2010打开附件
一、基本用法:
Private Sub UserForm_Initialize() '
'+++++++++++++++++++++++ 基本用法
With ComboBox3
.AddItem "办公室"
.AddItem "财务部"
.AddItem "营销部"
End With
ComboBox4.List = Array("办公室", "财务部", "营销部")
'++++++++++++++++++ 基本用法之连续数字
With ComboBox5
.Clear
For iii = 2008 To 2015
.AddItem iii
Next iii
.ListIndex = 0
End With
End Sub
二、连接工作表
Private Sub UserForm_Initialize() '
With Sheets("数据库") '数据库是工作表,选择不重复值
For i = 2 To .[A65536].End(xlUp).Row
For j = 0 To ComboBox1.ListCount - 1
If .Cells(i, 1) = ComboBox1.List(j) Then GoTo 100
Next j
ComboBox1.AddItem .Cells(i, 1)
100:
Next i
End With
End Sub
三、连接ACCESS数据库
1、连接ACCESS2003数据库
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset'从VBE的"工具/引用"菜单中选择可引用"Microsoft ActiveX Data Object 2.X Library"项
Private Sub UserForm_Initialize() '
'Stpath = ThisWorkbook.Path & Application.PathSeparator & "\数据库.mdb" '数据库是Access2003,选择不重复值
cnn.Open "provider=Microsoft.jet.OLEDB.4.0;data source=" & Stpath
Sql = "Select distinct 部门分类 from 部门 order by 部门分类"
rst.Open Sql, cnn, adOpenKeyset, adLockOptimistic
rst.MoveFirst
'---数据库是Access,选择不重复值表示方法之一
Do Until rst.EOF
ComboBox2.AddItem rst.Fields("部门分类")
rst.MoveNext
Loop
'-------数据库是Access,选择不重复值表示方法之二
If rst.EOF Then Exit Sub
For ii = 1 To rst.RecordCount
ComboBox2.AddItem rst.Fields("部门分类")
rst.MoveNext
Next ii
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
End Sub
2、连接ACCESS2007/2010数据库
需从VBE的"工具/引用"菜单中选择可引用"Microsoft ActiveX Data Object 2.8 Library"项
需从VBE的"工具/引用"菜单中选择可引用"Microsoft Jet and Replication Objects 2.6 Library"项
连接数据库的方式已经不在是:
“provider=microsoft.jet.oledb.4.0;data source=..........”
新的连接方式为:
“Provider=Microsoft.ACE.OLEDB.12.0;Data Source=......”
具体如下:
Dim strSQL As String
Dim rst As New ADODB.Recordset
Private Sub UserForm_Initialize() '
Stpath = ThisWorkbook.Path & Application.PathSeparator & "数据库.accdb" '设定access2010文件路径
cn.Provider = "Microsoft.ACE.OLEDB.12.0"
strCn = "Data Source =" & Stpath & ";Jet OLEDB:Database Password=" & ""
cn.Open (strCn)
strSQL = "Select distinct 部门分类 from 部门 order by 部门分类"
rst.Open strSQL, cn, adOpenStatic
If rst.EOF Then Exit Sub
For i = 1 To rst.RecordCount
ComboBox2.AddItem rst.Fields("部门分类")
rst.MoveNext
Next i
End Sub
[ 本帖最后由 EH2003 于 2011-3-7 23:49 编辑 ] |
评分
-
1
查看全部评分
-
|