Perhaps I've spent too much time in .NET, but it seems odd that I cannot easily pass the current Record of an ADO RecordSet to another method.
Private Sub ProcessData(data As ADODB.Recordset)
While (Not data.EOF)
ProcessRecord ([data.CurrentRecord]) ' <-- There is no CurrentRecord property.
data.MoveNext
Wend
End Sub
Private Sub ProcessRecord(singleRecord As ADODB.Record)
' Do stuff.
End Sub
The scant info I've found on the subject says to pass the entire RecordSet or to create a new Record and manually copy each field to it.
StackOverflow, is there a better way?
Personally, I would pass the entire recordset in to the ProcessRecord subroutine. Recordsets are always passed by reference so there is no overhead (performance or memory consumption) passing a recordset around. Just make sure you don't move to the next record in the ProcessRecord subroutine.
you can use the GetRows() method to load the data into an array and then let ProcessRecord work only with the array, but that 'disconnects' the method from the dataset and this may not be what you intend.
The GetRows() method takes optional arguments to specify how many rows to get, where to start and the fields to get
So:
ProcessRecord(data.GetRows(1,adBookmarkCurrent))
should do it for all fields
Unfortunately no.. you cant extract a single Record from a Recordset.. as G. Mastros said there is no additional overhead passing the whole recordset by reference and work with the current record so you might as well do it like that
Related
I want to get the next value of the field next to the current row.
I used ADODB movenext and moveprevious together, but there is an error that the current context does not permitted.
How to fix that?
This is the code
objresultset.MoveNext()
yMark = objresultset.Fields(k1).Value
If xMark = yMark Then
m += 1
End If
objresultset.MovePrevious()
I'm not sure. Perhaps you provide too little information.
I assume that ADO recordset features might also dependent upon the underlying database system and/or your database connection properties. So perhaps your specific database/recordset instance does not support MovePrevious in your case.
But if it has worked before, or if it works in a small test application, perhaps you are trying to move beyond the last record in your recordset. In that case you might check the BOF/EOF property values before you try to use MovePrevious/MoveNext.
I have a list of objects that are "keys" into a table - the keys are simply the items in the first column. They can be Integers or Strings, depending on what DB table we read it from. Since we use them a lot, we cache that column in an ArrayList called "Keys".
We wrote cover methods to return Row, one that uses strings and the other integers. If you call the integer version it simply returns that row by index. If you call the string, it looks down Keys for a match, and uses that index to pull out the row.
Ok, so now I pass Keys to Excel, pull out one of them in a loop, and ask it what it is...
TypeName(DB.Keys(i))
And the object returns...
Long
Great, the keys must have been integers! So now I'll try to get the row for that key, by calling the accessor method, Row...
DB.Row(DB.Keys(i))
And it calls into the version that takes a String.
Whoa!
Can anyone think of a reason that VBA calling back into our VB.net DLL ends up calling the wrong accessor?
ADDED CODE: I can't figure out how to put the code in as a reply, so I'm editing this. Here is the code in the VB.net class:
Public Function Row(ByVal K As String) As DataRow
Dim R As DtaRow = DB.Tables(0).Rows(K)
Return New DataRow(R)
End Function
Public Function Accounts(ByVal K As Integer) As DataRow
Dim R As DtaRow = DB.Tables(0).Rows(K)
Return New DataRow(R)
End Function
If you're wondering, there's two versions of Rows, which take strings or ints.
This code works perfectly from VB.net. You can ask for a row by key string or by the row number, that invokes the proper Row, which calls the proper Rows, and out comes the proper answer.
But in VBA, it always calls the method with the string input. If I rename it to RowIHATEYOUALL then I can call the Integer version just fine. But when there are two of them, differing only in signature, no such luck.
And the A and i (see comments) was my typo.
The interop layer does not support overloaded methods. Whenever you call Row, the first declared method with that name is used. The .NET overload resolution algorithm does not apply here.
Other overloads are exposed to VBA as Row_2, Row_3, etc. Thus, the following code should do what you expect:
DB.Row_2(DB.Keys(i))
This implicit dependency on the order of declaration has a high potential for error. Thus, I would suggest to either
give the methods unique names if they are called from VBA,
or, if you want to retain the "nice" overloaded version for .NET, add compatibility methods for VBA:
<Obsolete("Compatibility method for VBA, use Row instead.")>
Public Function RowByKeyVBA(ByVal K As String) As DataRow
Return Row(K)
End Function
<Obsolete("Compatibility method for VBA, use Row instead.")>
Public Function RowByNumberVBA(ByVal K As Integer) As DataRow
Return Row(K)
End Function
Further information can be found in the following question:
COM->.NET - can't access overloaded method
Following Heinzi's notes (above) I fixed this by making three method signatures for each call, one takes an Object and then attempts to figure out what it is, the others take the String and Integers. Within VB/C#/etc the proper String or Integer methods get called as expected, from VBA the Object version is called, as Heinzi noted
This causes the very minor issue that a user may have a "number like value" that is actually a String. For instance, the array keys might be "User3232" or "3232", both of which are String objects in the table. So you have to be careful, simply asking if the Object can be converted to an Int32 is not enough. This is unlikely to be something that effects most users.
On this Access form I am working on I have a global variable that take its value from another form on its Form_Load event. For some reason unknown to me the variable "loses its value" (becomes = "") after some time elapses or some event occurs. I have not been able to notice anything in particular that triggers this behaviour. Are global variables reset after some time of "inactivity" on the form ?
Here is how I set the global variables I am talking about:
Private Sub Form_Load()
'...
Set prev_form = Form_Identification.Form
PasswordSybase = prev_form.Password.Value & vbNullString
UserSybase = prev_form.UserID.Value & vbNullString
'...
End Sub
An alternate solution (Only 2007 and onwards) I've started using is TempVars instead of globals in the odd situation I "needed" something global. It's a collection and it persists for the duration of the application unless you explicitly release it. So in some cases I feel its more useful than globals and in some cases worse.
TempVars.Add myVarName, myVarValue ' To initialize
TempVars.Item(myVarName) = newVarValue ' To reference and assign a new value
TempVars.Remove(myVarName) ' To release
Quick search should show you more lot references, but I've included link to a basic one
http://blogs.office.com/b/microsoft-access/archive/2010/09/27/power-tip-maximize-the-user-of-tempvars-in-access-2007-and-2010.aspx
I do hope that visitors see this post, as it provides an important additional piece.
Even if you declare a variable globally, it appears that - in the event that you set that variable's value in a form module - that value is lost when you UNLOAD the form.
The solution (in my case) was as simple as replacing:
Unload Me
...with...
Me.Hide
The variables (and objects) that I set in that code module then retained their values through the entire lifetime of the application instance.
This may help:
https://accessexperts.com/blog/2011/01/12/multi-session-global-variables/
Juan Soto explains how to use a local table to keep variables and how to call them when needed. It may serve your purpose in 2000 since TempVars isn't an option. You could always delete the variables "on close" of the database so that UID and PWD aren't kept.
You can create a "fake" global variable by
creating a form (e.g. named frmGlobal)
make sure the form is always open but hidden
create a TextBox for each global variable you want (e.g. tVar1)
in your code, reference as e.g. Form_frmGlobal.tVar1
The disadvantage is that an unbound text box may not give you a specific data type you want
The two ways around that are
in your code, explicitly convert the textbox to the data type when referencing the global variable
e.g Clng(Form_frmGlobal.tVar1)
another option is create a one-row table and bind your textboxes on your hidden form to the table, so your data types are enforced
A bonus of this method is you can use for persistent storage between sessions
Caveat: make sure this table is local to a single user only, in the front end database file (don't want to put it in the back end database because of multi-users over-writing each other). This assumes you are using front end + back end separated databases, with distribution of front end to each user's workstation.
I see nothing in that statement that tells me it's a global variable. You set global variables above ALL Subs/Functions and below an Options Compare statement in a module, by stating:
PUBLIC X as string
Any other variable is only good until the sub or function has completed.
Also, Global variables MUST be declared on a PROPER MODULE. You can't declare them on a form's module.
I just installed Visual Studio 2010 Service pack (proposed on Windows Update), and I can see a new feature on the "intellisense" that means when I write a Function or Sub in VB.NET it doesn't auto-complete parameters with ByRef or ByVal...
1) Is there anyway that I can configure this option back to how it was before?
2) If I don't specify ByX, which one is used by default? (it seems like it is always ByRef)
It seems that this post covers your question:
http://msmvps.com/blogs/carlosq/archive/2011/03/15/vs-2010-sp1-changing-quot-byval-quot-vb-net-code-editor-experience.aspx
So no, there is no way to get the old behaviour. From now on ByVal is the default (what it was before) and it won't get added automatically to the method parameters.
In my opinion this is a good decision since it's making VB.NET a bit more consistent with C# and avoids unnecessary "noises"(it's already verbose enough).
Old behaviour:
Private Sub test(ByVal test As String)
End Sub
New behaviour
Private Sub test(test As String)
End Sub
Tim covered what you asked directly, but something else to keep in mind is that any reference type variable, like a user defined class even if passed by value will allow you to make changes to that instances properties etc that stay. It won't however allow you to change the entire object. Which may be why it seemed to you to be defaulting to by reference
Public Sub (Something As WhateverClass)
Something = New WhateverClass 'will result in no changes when outside this method
Something.Property1 = "Test" 'will result in an updated property when outside this method
End Sub
From MSDN:
The value of a reference type is a pointer to the data elsewhere in memory.
This means that when you pass a reference type by value,
the procedure code has a pointer to the underlying element's data,
even though it cannot access the underlying element itself. For
example, if the element is an array variable, the procedure code does
not have access to the variable itself, but it can access the array
members.
Beware when transferring routines to VBA, where the default is ByRef (see, e.g., "The Default Method Of Passing Parameters" at the bottom of this page, by the great Chip Pearson).
That can be messy.
I'm making a Library type app which needs to scan the whole computer when it is run for the first time. Not again ever. How can I accomplish it?
I'll be using SQL database to store data. So, I can easily make a table there and store a flag and check it on first run, but is there any other way? Any native support for this in VB.NET?
Use either
Deployment.Application.ApplicationDeployment.CurrentDeployment.IsFirstRun
or
My.Application.Deployment.IsFirstRun
Edit:
Check this article for additional info.
I found the best way to be to use appsettings..
Using your SQL database seems like a viable solution. You can also write a flag to a settings file on the file system if you don't want to use a table to hold it. This is a pretty good site with some examples on how to write to a file.
http://www.freevbcode.com/ShowCode.asp?ID=4492
EDIT: If you're looking for a way to determine, using some native feature of VB.NET, whether a method has ever been run before (as in, last year), I think you're out of luck. That said, a quick-and-dirty approach might be to define a method to query the database for the flag you've referred to and store the result of that method in a static flag.
Public Sub MethodToRunOnlyOnce()
' this flag will maintain its value between method calls '
' in the same session '
Static methodAlreadyRun As Boolean = MethodHasBeenRun()
If methodAlreadyRun Then
Exit Sub
End If
Try
' ... code ... '
Finally
MethodToSetDatabaseFlag()
methodAlreadyRun = True
End Try
End Sub
Private Sub MethodToSetDatabaseFlag()
' code here to set Db flag '
End Sub
Private Function MethodHasBeenRun() As Boolean
' code here to check Db flag '
End Function
You could always store this flag in an xml file or in the registry so it's on the PC. If you store it in a database and there are multiple copies of this program running on different PCs, you would have to identify them in the DB somehow, whereas if you keep track of it locally you don't need to worry about it.