vba command call procedure

本文介绍如何使用VBA连接Oracle数据库,并演示创建记录集、引用记录集结果及调用不同类型的存储过程的方法。
部署运行你感兴趣的模型镜像
simple sample

▲连接Oracle数据库

Set cnn = CreateObject("ADODB.Connection")
cnn.Open "Provider=msdaora;Data Source=dl580;User Id=emssxjk;Password=emssxjk;"


dl580是tnsnames.ora中配置的服务名。

▲创建记录集recordset

Set rst = CreateObject("ADODB.Recordset")
sqls = "select * from tb_city"
Set rst = cnn.Execute(sqls)

这儿的SQL语句除了查询语句select以外,也可以用insert、update、delete等命令,也可以用truncate table这样的命令。这些SQL语句也可以用command对象完成。command对象还可以进行存储过程的调用并传递参数。


▲记录集结果的引用

Excel VBA 通过ADO取到数据后,有如下引用方式(假定记录集名字为rst):

1、字段数量:rst.fields.count;

2、字段名称:rst.fields(0).name,0表示第一个字段,其它字段分别是1,2,...rst.fields.count-1;

3、字段值:rst(0)或者rst(0).Value或者rst.fields(0).value,0表示第一个字段,也可以用字段名代替,如:rst("city");

4、整个记录集: Range("a2").CopyFromRecordset rst命令将记录集保存到A2单元格开始的工作表中;

5、记录移动:取数后记录定位在第一条,rst.movenext可以移动到下一条,结尾标志:rst.eof = true,Excel VBA只支持向前移动(rst.movenext);

6、记录数:rst.RecordCount是反馈记录数的,但在VBA中却总是反馈-1,不过可以根据rst.eof判断有无查询结果,如果rst.eof= true就表示查询结果为空。

▲调用存储过程

1、连接数据库,如前;

2、定义存储过程

Set cmd = CreateObject("ADODB.Command")

Set cmd.ActiveConnection = cnn
cmd.CommandText = "zfqf_bag2mail" '存储过程名称,有两个参数
cmd.CommandType = adCmdStoredProc

3、参数赋值

cmd.Parameters(1).Value = Cells(row1, pos_acc)
cmd.Parameters(2).Value = Cells(row1, pos_lab)
4、执行存储过程

cmd.Execute

这个存储过程的结果保存在表中,通过查询语句得到结果,没有通过变了返回。


1,不带参数的,直接在连接或Recordset 中用“EXEC 过程名”调用即可。
Private Sub cmdPrepareNewMinSalary_Click()
Dim conEmployees As ADODB.Connection
Dim strProcedure As String

Set conEmployees = Application.CurrentProject.Connection
strProcedure = "CREATE PROCEDURE SetNewMinSalary " & _
"AS " & _
"Update Employees " & _
"SET HourlySalary = 12.50;"

conEmployees.Execute strProcedure
conEmployees.Close
End Sub
调用程序如下:
Private Sub cmdNewMinSalary_Click()
Dim conEmployees As ADODB.Connection
Dim strProcedure As String

Set conEmployees = Application.CurrentProject.Connection
strProcedure = "EXECUTE SetNewMinSalary;"

conEmployees.Execute strProcedure
conEmployees.Close
End Sub

2,带一个参数的,也可以直接调用,如下例子
Private Sub cmdCreateProcedure_Click()
Dim conEmployees As ADODB.Connection
Dim strProcedure As String

Set conEmployees = Application.CurrentProject.Connection
strProcedure = "CREATE PROCEDURE SetNewMinSalary " & _
"(NewMinSalary Currency) " & _
"AS " & _
"Update Employees " & _
"SET HourlySalary = NewMinSalary " & _
"WHERE HourlySalary < NewMinSalary;"

conEmployees.Execute strProcedure

MsgBox "The new stored procedure has been created."
conEmployees.Close
End Sub

调用时直接输入一个参数。
Private Sub cmdExecuteProcedure_Click()
Dim conEmployees As ADODB.Connection
Dim strProcedure As String

Set conEmployees = Application.CurrentProject.Connection
strProcedure = "EXECUTE SetNewMinSalary 14.50;"

conEmployees.Execute strProcedure

MsgBox "The minimum hourly salary has been set to 14.50/hr"
conEmployees.Close
End Sub

3:最麻烦的是带有多参数的,如下面的例子带有两个参数。
直接从SQL server复制过程如下:
CREATE PROCEDURE [dbo].[Max_2ExcelDB]
(
@Territory varchar(10)='All',
@Country varchar(10)='CN'
)
AS
set nocount on
if @Territory='All'
BEGIN
select * from CustomerDB
set nocount off
END
else
begin
select a.* from CustomerDB a left join DistributorDB b
on a.Distributor=b.Distributor
where b.Territory in (@Territory,'Open') and a.Country=@Country
end
set nocount off
调用程序如下,这时候就要请出ADODB.Command对象了:
Sub CallmyProc()
Dim conn As ADODB.Connection
Dim MyProc As ADODB.Command

Dim sSql As String
Dim SrcArr

Set conn = New ADODB.Connection
Set MyProc = New ADODB.Command
conn.ConnectionString = connStr(1)
conn.Open

If conn.State = adStateOpen Then
With MyProc
.ActiveConnection = conn
.Prepared = True
.CommandText = "Max_2ExcelDB"
.CommandType = adCmdStoredProc
.Parameters.Append .CreateParameter("@Territory", adChar, adParamInput, 10, "South")
.Parameters.Append .CreateParameter("@Country", adChar, adParamInput, 10, "CN")
ThisWorkbook.Sheets("sheet4").Cells(1, 1).CopyFromRecordset .Execute
End With
Else
MsgBox " 无法打开数据库"
End If

conn.Close
Set conn = Nothing
Set MyProc = Nothing
End Sub

4,更麻烦的是带有多参数,还有返回参数的,也是用Adodb.command对象解决。下面代码来自网络http://www.officefans.net/cdb/viewthread.php?tid=91224:
Set 连接 = CreateObject("ADODB.Connection")
Set 过程 = CreateObject("ADODB.Command")
连接.Open "Driver={SQL Server};Server=192.168.1.2;Database=数据库名_A;uid=共用登录;pwd=123456"
起始日期="2007-12-1"
截止日期="2008-3-1"
With 过程
.ActiveConnection = 连接
.Prepared = True
.CommandText = "vba_分数统计"
.CommandType = 4
.Parameters.Append .CreateParameter("@起始日期", 200, 1, 20, 起始日期) ‘append 与后面的点. 需要加空格,即将createparameter返回值传给append方法。
.Parameters.Append .CreateParameter("@截止日期", 200, 1, 20, 截止日期)
.Parameters.Append .CreateParameter("@姓名", 200, 1, 50, Worksheets(2).Cells(2, 1).Value)
.Parameters.Append .CreateParameter("@返回分数", 2, 2)
.Execute
Worksheets(1).Cells(1,1).Value = .Parameters("@返回分数")
.Close
Set 连接 = Nothing
end with

create PROCEDURE pro1 
@id int=10,
@count int output
AS
BEGIN
select @count=COUNT(*) from test1 where id>@id;
end

既能返回数据集又能输出参数。
With command
.ActiveConnection = con
.CommandType = adCmdStoredProc
.CommandText = "pro1"
.Parameters.Append .CreateParameter(Name:="@id", Value:=0, Type:=adInteger)
.Parameters.Append .CreateParameter(Name:="@count", Type:=adInteger, Direction:=adParamOutput)
Set rs = .Execute()
MsgBox .Parameters("@count").Value
End With



-----------------------------

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

<think>好的,用户想了解如何在Excel VBA中使用CommandBars。首先,我需要回忆一下CommandBars的相关知识。记得CommandBars是控制Excel菜单栏和工具栏的对象,可以用来添加、删除或修改菜单项。用户的问题可能涉及如何获取现有菜单栏,如何添加自定义菜单,或者如何修改现有命令的可见性等。 根据用户提供的引用内容,特别是引用[4]中提到CommandBars集合的表示方法和Controls的使用,应该先介绍基本概念,比如如何引用不同的命令栏。例如,CommandBars(index)或CommandBars("名称")。可能需要举几个例子,比如如何获取单元格右键菜单,即CommandBars("Cell")。 接下来,用户可能需要具体的操作步骤,比如如何添加新的菜单项。引用[3]中的代码展示了如何通过Controls.Add方法添加按钮,并设置属性如Caption、OnAction等。这部分应该详细说明,包括参数的使用,比如before参数的位置,BeginGroup添加分隔线,以及如何关联宏。 另外,用户可能对如何隐藏或禁用现有菜单项感兴趣,引用[2]中的例子展示了如何设置Visible属性为False。这里需要注意不同菜单项的路径,比如“工具(&T)”下的“选项(&O)”,可能需要说明如何正确引用多级菜单。 还需要考虑不同菜单类型,比如弹出式菜单(msoBarTypePopup)和普通工具栏(msoBarTypeNormal)。引用[5]提到菜单项的类型,比如msoControlButton和msoControlPopup,这可能在添加子菜单时有用,需要解释如何创建带子菜单的项。 用户可能还会遇到错误处理的问题,比如在删除已存在的菜单项时使用On Error Resume Next来避免错误。引用[3]中的代码有相关示例,应该提到这一点。 最后,需要总结一些常见应用场景,比如自定义右键菜单、隐藏内置功能等,并给出注意事项,比如兼容性问题,特别是在不同Excel版本中CommandBars的变化。同时,提醒用户使用后恢复原有设置,避免影响其他用户。 需要确保回答结构清晰,分步骤说明,并包含代码示例,帮助用户实际操作。同时,检查是否有遗漏的要点,比如如何遍历所有CommandBars,或者如何设置图标(FaceId)等。可能还需要提到如何删除自定义菜单项,确保代码的完整性。</think>在Excel VBA中,`CommandBars`是控制菜单栏、工具栏和快捷菜单的核心对象。以下是具体使用方法的分步说明: --- ### 一、基础概念 1. **CommandBars集合** - 表示Excel中所有内置/自定义菜单栏和工具栏,包含三种类型: $$ \text{msoBarTypeNormal(常规工具栏), msoBarTypeMenuBar(菜单栏), msoBarTypePopup(快捷菜单)}$$ - 引用方式: ```vba '通过索引号 CommandBars(1) '通过名称(推荐) CommandBars("Worksheet Menu Bar") '工作表菜单栏 CommandBars("Cell") '单元格右键菜单[^3] ``` 2. **Controls集合** 每个`CommandBar`对象包含多个控件(菜单项),可通过层级访问: ```vba CommandBars("Worksheet Menu Bar").Controls("工具(&T)").Controls("选项(&O)...") ``` --- ### 二、常用操作 #### 1. 获取所有菜单栏名称 遍历所有CommandBars并输出名称: ```vba Sub ListCommandBars() Dim cb As CommandBar For Each cb In Application.CommandBars Debug.Print cb.Name & " - Type: " & cb.Type Next End Sub ``` #### 2. 隐藏内置菜单项 通过设置`Visible`属性隐藏"工具-选项": ```vba CommandBars("Worksheet Menu Bar").Controls("工具(&T)").Controls("选项(&O)...").Visible = False [^2] ``` #### 3. 添加自定义菜单项 在单元格右键菜单添加"朗读"功能: ```vba Sub AddCustomMenu() On Error Resume Next '防止重复添加报错 Application.CommandBars("Cell").Controls("朗读").Delete '先删除旧项 With Application.CommandBars("Cell").Controls.Add(Type:=msoControlButton, Before:=1) .Caption = "朗读" .BeginGroup = True '添加分隔线 .FaceId = 186 '设置图标 .OnAction = "SpeakMacro" '关联宏 End With End Sub Sub SpeakMacro() MsgBox "正在朗读:" & ActiveCell.Value End Sub ``` #### 4. 创建带子菜单的项 添加包含子菜单的弹出式控件: ```vba With CommandBars.Add("MyMenu", msoBarPopup) With .Controls.Add(Type:=msoControlPopup) .Caption = "数据分析" With .Controls.Add(Type:=msoControlButton) .Caption = "生成图表" .OnAction = "ChartMacro" End With End With .ShowPopup '显示弹出菜单 End With ``` --- ### 三、注意事项 1. **类型匹配** - 普通按钮用`msoControlButton` - 弹出菜单用`msoControlPopup`[^5] 2. **FaceId图标库** 内置图标代码可通过`CommandBarButton.FaceId`属性查询,例如: - 保存图标:3 - 打印图标:4 - 常用操作图标范围:1-4000+ 3. **兼容性问题** Excel 2007及以上版本部分菜单栏已被Ribbon替代,建议配合`RibbonX`实现更复杂功能。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值