我没有太多使用VB,但据我所知,范围与C#相同。问题是,我在MS Access中使用VB,所以我不确定规则是否有点不同(尽管我认为它们不是)。以下代码显示分配给仅在函数参数中声明的变量的值。特别是看看PurchaseOrderID,我不确定它是如何保留其指定值以便在进行它的函数中使用。
Function Create(SupplierID As Long, EmployeeID As Long, OrderID As Long, PurchaseOrderID As Long) As Boolean
Dim rsw As New RecordsetWrapper
If rsw.OpenRecordset("Purchase Orders") Then
With rsw.Recordset
.AddNew
![Supplier ID] = SupplierID
If EmployeeID > 0 Then
![Created By] = EmployeeID
![Creation Date] = Now()
![Submitted By] = EmployeeID
![Submitted Date] = Now()
![Status ID] = Submitted_PurchaseOrder
End If
If OrderID > 0 Then
![Notes] = InsertString(PurchaseGeneratedBasedOnOrder, CStr(OrderID))
End If
If rsw.Update Then
.Bookmark = .LastModified
PurchaseOrderID = ![Purchase Order ID]
Create = True
End If
End With
End If
End Function
Function CreateLineItem(PurchaseOrderID As Long, ProductID As Long, UnitCost As Long, Quantity As Long) As Boolean
Dim rsw As New RecordsetWrapper
If rsw.OpenRecordset("Purchase Order Details") Then
With rsw.Recordset
.AddNew
![Purchase Order ID] = PurchaseOrderID
![Product ID] = ProductID
![Quantity] = Quantity
![Unit Cost] = UnitCost
CreateLineItem = rsw.Update
End With
End If
End Function
有人可以给我一些见解吗?
答案 0 :(得分:2)
在VBA中,如何调用过程非常重要。
“即使被调用的过程已将其参数声明为ByRef,您也是 可以通过将每个参数括在其中来强制那些为ByVal 括号“。
- http://www.cpearson.com/excel/byrefbyval.aspx
所有Office应用程序中的VBA都是如此。例如,假设您有两个程序:
Sub SubByVal(ByVal Total As Integer)
Total = 50
End Sub
Sub SubByRef(ByRef Total As Integer)
Total = 50
End Sub
你做了几个测试:
Dim Total As Integer
Total = 100
这三个版本按预期工作,Total等于100
Call SubByVal(Total)
SubByVal (Total)
SubByVal Total
这两个按预期工作,总计等于50
Call SubByRef(Total)
SubByRef Total
然而,在这个版本中,尽管调用了ByRef,Total等于100,因为它被括号强制为ByVal。
SubByRef (Total)
答案 1 :(得分:2)
也许这最好由类型来处理。像这样:
Type PurchaseSet
PurchaseOrderID As Long
OrderCreated as boolean
End Type
Function Create(SupplierID As Long, EmployeeID As Long, OrderID As Long ) As PurchaseSet
Dim rsw As New RecordsetWrapper
Dim ps as PurchaseSet
ps.OrderCreated = false
If rsw.OpenRecordset("Purchase Orders") Then
With rsw.Recordset
.AddNew
![Supplier ID] = SupplierID
If EmployeeID > 0 Then
![Created By] = EmployeeID
![Creation Date] = Now()
![Submitted By] = EmployeeID
![Submitted Date] = Now()
![Status ID] = Submitted_PurchaseOrder
End If
If OrderID > 0 Then
![Notes] = InsertString(PurchaseGeneratedBasedOnOrder, CStr(OrderID))
End If
If rsw.Update Then
.Bookmark = .LastModified
ps.PurchaseOrderID = ![Purchase Order ID]
ps.OrderCreated = True
End If
End With
End If
Create = ps
End Function
答案 2 :(得分:1)
您可以按值或引用将参数传递给VBA过程。如果您未在过程声明中指定ByVal
或ByRef
,则默认为ByRef
。所以以下两个声明是等效的......
Function DoSomething(PurchaseOrderID As Long) AS Boolean
Function DoSomething(ByRef PurchaseOrderID As Long) AS Boolean
这里的关键是ByRef
允许将过程中的参数更改传回给调用者。