Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    Visual Basic




Ackerman Function - Recursive Function Help Needed


I recently had to write the following function in maple known as the Ackerman function. However I need to write a function in VBA to calculate it.

The function in maple was the following.

a:=proc(n,m)
if n=0 then RETURN(m+1) fi;
if m=0 then RETURN(a(n-1,1)) fi;
RETURN(a(n-1,a(n,m-1)));
end;


The problem I am having is getting the function to stop iterating. It wont calculate a result even for simple results like T(1,1).

The code I have written in VB is as follows.



Function T(n As Integer, m As Integer)

If m = 0 Then
T(n, m) = T(n - 1, 1)
End If

If n = 0 Then
T(n, m) = m + 1
End If

T(n, m) = T(n - 1, T(n, m - 1))
End Function



Any Ideas? Is it possible

Cheers

Rich




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Recursive Function
ok i need to create a recursive fuction that goes through an aray of 25 and finds the highest vallue, help?

Recursive Function
I am trying to write a simple recursive function in Visual Studio Express 2005. Any help would be greatly appriciated:

I am receiving the following error when I try to execute the below code:

Error: 61837 - Unable to write read-only property.

VB Code:
Public Function RemoveUserFromUserClasses(ByRef objUserClass As Object, ByRef objUser As Object) As Boolean         On Error GoTo Err_RemoveUserFromUserClasses         'Counter        Dim I As Long        'Hold the current User Class        Dim objCurUserClass As Object          ' For each UserClass remove the user.        If objUserClass.Count > 0 Then            For I = 1 To objUserClass.Count                objCurUserClass = objUserClass.Item(I)                objCurUserClass.Users.Remove(objUser)                RemoveUserFromUserClasses(objCurUserClass.UserClasses, objUser)            Next I        End If  Exit_RemoveUserFromUserClasses:        Exit Function Err_RemoveUserFromUserClasses:        If fLogFileOpen Then            PrintLine(intLogFileNumber, Str(Now.ToOADate) & ": * * * RemoveUserFromUserClasses Error: " & Err.Number & " - " & Err.Description)        End If        Resume Exit_RemoveUserFromUserClasses     End Function










Edit: Added [vbcode][/vbcode] tags for more clarity. - Hack

Recursive Function Help
Last night I spent forever trying to figure out how to do this. Could somebody tell me how to get started, maybe provide some example code?

Thanks

Recursive Function
Urgent!! I wrote a recursive function. This recursive function will start when I click on the 'Start' button. I need to stop this recursive function when I click on the 'Stop' button, but the 'Stop' button only responce after the recursive function finish, how can I always listen to the 'Stop' button event so I can terminate the recursive function any time as I want? Thanks.

Recursive Function
here is what am trying to do
let say i have a directory called
c:ARTISTS

thats the root
in that directory there is let say 30 different artits
and in those artists SOME can have more than one album
those that dont have more than one album
the songs are located in just the name of the artist

so if artst1 had one album
all the songs would be located in c:Artistsartist1

and if artist2 had 2 albums
it would be like
c:artistsartist2album1 (songs for this album go here)
c:artistsartist2album2 (songs for album2 go here)

so i would like someone to help me out with making a function that when given c:artist
it will go into every directory
and copy artist name(directory), album name( sub directory), and song names (filenames)
into a table..

thank you

Recursive VB Function?
Hi all,
I am looking for a recursive function to step through a tree like structure. What make this difficult is that each child node in the tree only knows if it has a child. It does not know about its parent. My problem is that I can recurse through the tree, moveing to each child nodes child, but I can not return to the previous levels. I do not know how many level deep I need to go, so it must be recursive.

Below is a typical tree structure I will need to recurse. I start at A, then I can get to ABC1. But how to I return to AB1 and continue the process? As you can see, the tree can be many levels deep and I only know if the node has a child and how to get to that child.

A
l
A1------->A1.1
l l
A2 AB1-------->AB1.1
l l l
A3 l ABC1
l AB2----------------------->AB2.1
A4 l l
l AB3 D1---------------->D1.1
A5 l l
l D2 F1
A6------->A6.1 l
                 l F2
               B1---------->B1.1----------->C1
                                      l l
                                    B2.1 C2
                                       l
                                     B3.1

Thanks



Edited by - skyodyssey on 7/30/2004 12:12:31 PM

Recursive Algorithm/Function
Does anyone know how create a Recursive Algrithm in VB? Any help would be greatly aprciated.
Thx

Problem With Recursive Function
Hi

I have a problem with the following code:


VB Code:
Private scanData() As String Private Sub Form_Load()List1.AddItem "c:My Documents"List1.AddItem "e:"End Sub Private Sub Command1_Click()scanfolders3End Sub Public Sub scanfolders3()Dim startTime, elapTime As DoubleDim startFolder As StringDim scanResult As BooleanscanResult = FalseForm1.MousePointer = vbHourglassstartTime = CDbl(Timer)ReDim scanData(4, 0)startFolder = List1.TextscanResult = scanFolders(startFolder)elapTime = CDbl(Timer) - startTimeForm1.MousePointer = vbNormalText1.Text = elapTimeEnd Sub Public Function scanFolders(fpath As String) As BooleanDim x As DoubleSet fso = CreateObject("Scripting.FileSystemObject")    For Each fl In fso.GetFolder(fpath).Files        x = UBound(scanData, 2) + 1        ReDim Preserve scanData(4, x)        scanData(0, x) = fl.Name        scanData(1, x) = fpath        scanData(2, x) = fl.Size        scanData(3, x) = fl.Type        DoEvents        x = x + 1    Next fl    For Each fldr In fso.GetFolder(fpath).SubFolders        scanFolders fldr.Path    Next fldrSet fso = NothingSet fldr = NothingSet fl = NothingscanFolders = TrueEnd Function


The main aim of the code is to populate an array with the details of files in a given directory. The form has been added to assess the performance for various drives/directories.

The problem is that subsequent runs of the code take relatively longer each time. Given that "e:" is a 512mb pendrive with about 300mb used and that "c:My Documents" contains about 4GB typical results with times in seconds are:

e: 4.56
e: 4.63
e: 4.45
c:My Documents 17.68
e: 18.11
c:My Documents 86.45
e: 77.5

I can't see where the resources are leaking or what is causing this build up after the larger directory is scanned.

Things I've tried are:

1. Not using Preserve - although this wouldn't work as needed anyway it was no quicker.
2. Commenting out DoEvents - Didn't help

Any ideas?

Thanks

Mouse

Making A Recursive Function
Hi, I need help making a recursive function for the code listed
below.
I posted here previously for solution to listing all subkeys
and values of a registry key. I got the code to do it, but
it only lists on level, so it needs to be put in a recursive
function in order to go through the entire branch.
I've tried to do this but I never worked with recursion before
and I can't get it to work.
I just need to add all the keys and values to a list in this
format:
Key
if it is a key or if it is a value:
Key,value=data

This code does that all but only one step. Can someone
help me with this, it is a one minute job for someone who
worked with recursion before. Thanks in advance.


VB Code:
Const ERROR_NO_MORE_ITEMS = 259&Const HKEY_CURRENT_CONFIG = &H80000005Const HKEY_LOCAL_MACHINE = &H80000002Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As LongPrivate Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA" (ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As LongPrivate Declare Function RegEnumKeyEx Lib "advapi32.dll" Alias "RegEnumKeyExA" (ByVal hKey As Long, ByVal dwIndex As Long, ByVal lpName As String, lpcbName As Long, ByVal lpReserved As Long, ByVal lpClass As String, lpcbClass As Long, lpftLastWriteTime As Any) As LongPrivate Declare Function RegEnumValue Lib "advapi32.dll" Alias "RegEnumValueA" (ByVal hKey As Long, ByVal dwIndex As Long, ByVal lpValueName As String, lpcbValueName As Long, ByVal lpReserved As Long, lpType As Long, lpData As Any, lpcbData As Long) As LongPrivate Sub Form_Load()    Dim hKey As Long, Cnt As Long, sName As String, sData As String, Ret As Long, RetData As Long    Const BUFFER_SIZE As Long = 255    'Set the forms graphics mode to persistent    Me.AutoRedraw = True    Me.Print "RegEnumKeyEx"    Ret = BUFFER_SIZE    'Open the registry key    If RegOpenKey(HKEY_LOCAL_MACHINE, "Hardware", hKey) = 0 Then        'Create a buffer        sName = Space(BUFFER_SIZE)        'Enumerate the keys        While RegEnumKeyEx(hKey, Cnt, sName, Ret, ByVal 0&, vbNullString, ByVal 0&, ByVal 0& ) <> ERROR_NO_MORE_ITEMS            'Show the enumerated key            Me.Print "  " + Left$(sName, Ret)            'prepare for the next key            Cnt = Cnt + 1            sName = Space(BUFFER_SIZE)            Ret = BUFFER_SIZE        Wend        'close the registry key        RegCloseKey hKey    Else        Me.Print "  Error while calling RegOpenKey"    End If     'This part below lists the values and their data of selected key    Me.Print vbCrLf + "RegEnumValue"    Cnt = 0    'Open a registry key    If RegOpenKey(HKEY_LOCAL_MACHINE, "SoftwareMicrosoftWindowsCurrentVersion", hKey) = 0 Then        'initialize        sName = Space(BUFFER_SIZE)        sData = Space(BUFFER_SIZE)        Ret = BUFFER_SIZE        RetData = BUFFER_SIZE        'enumerate the values        While RegEnumValue(hKey, Cnt, sName, Ret, 0, ByVal 0&, ByVal sData, RetData) <> ERROR_NO_MORE_ITEMS            'show data            If RetData > 0 Then Me.Print "  " + Left$(sName, Ret) + "=" + Left$(sData, RetData - 1)            'prepare for next value            Cnt = Cnt + 1            sName = Space(BUFFER_SIZE)            sData = Space(BUFFER_SIZE)            Ret = BUFFER_SIZE            RetData = BUFFER_SIZE        Wend        'Close the registry key        RegCloseKey hKey    Else        Me.Print "  Error while calling RegOpenKey"    End IfEnd Sub

How To Write A Recursive Function?
Hi,

I'm trying to write a recursive function but in vain... thus i sincerely hope you could help me... Actually my purpose of this recursive search is to search for all children, grandchildren, great grandchildren...etc of a particular record. Suppose in my table, I have two fields, Parent and Child.

For example,

Parent Child
===== ====

May - John
Jess - Mike
Jess - Nick
John - Peter
John - Jess
John - Watson
Peter - Carrie

........ etc

Suppose I start with a name John. My aim is to 1st search thru the parent field for all records with parent, John. In this case, the records will be those of children Peter, Jess, and Watson.

For each of these children, I will search thru the table again, for their children (aka John's grandchildren)..

Thus I need a recursive method to traverse thru the records.

Can anyone help?

Thank you very very much.

Recursive Function Calls
In order to generate a unique number I wrote the following simple Function.  It fails to do the job because there is no recursive Function call. However, using an analogous Subroutine works because the desired recursive call to the Sub _does_ happen.

Is this a VB feature, and, if so, why?

Public gcollUniqNum as New Collection
Public glUniqNum as Long

Public Function UniqueNum() As Long
    Dim lNum As Long    
    lNum = GenRan(1)
    If InColl(gcollUniqNum, CStr(lNum)) = True Then

        'NO recursive call to UniqueKey.  
        'Function exited with UniqueKey = 0
        lNum = UniqueKey

    Else
        gcollUniqNum.Add lNum, CStr(lNum)
        UniqueNum = lNum
    End If
End Function

Public Sub GenerateUniqueNumber()
    Dim lNum As Long
    lNum = GenRan(1)
    If InColl(gcollUniqNum, CStr(lNum)) = True Then

        'DOES result in recursive call
        GenerateUniqueNumber
   
     Else
        gcollUniqNum.Add lNum, CStr(lNum)
        glUniqNum = lNum
    End If
End Sub



Public Function InCollection(collDesignated As Collection, Key As String) As Boolean
    On Error GoTo NotThere
    'VB generates a run-time error if Key is not in collDesignated
    If collDesignated.Item(Key) <> "" Then
        InCollection = True
        Exit Function
    End If    
NotThere:
End Function


 

Need Help With Treeview Vb6 Recursive Function
Hi ,
What I am trying to achieve is the ability to limit the checked nodes to 1 only.
Within the London's node there are 2 children (show1,show2) only one perfomance can be checked
In my attempt I set all to false and then the selected one to true.But i m failing to recursely loop.
Can you help?

Scenario

 Country
   City
       London
          show 1
             Cinderella 20/06/06 performance
             Cinderella 21/06/06     performance
          show 2
             Phantom 20/06/06    performance    
             Phantom 21/06/06    performance

My failed attempt
Code:

 Private Sub ValidateNodes(ByVal ndParent As MSComctlLib.Node)
                         
dim oChild as MSComctlLib.Node


        Set oChild = ndParent .Child
        For iIndex = 0 To ndParent .Children - 1
           oChild.Checked =false
           Set oChild = oChild.Next
        Next
        tvw.SelectedItem.Checked=true

End Sub


Thanks in advance

Recursive Function In Formula Not Working?
I am trying to use a recursive function to return the number of levels for a specific parent but once I put the function in an equation it doesn't work. I receive a "ByRef Argument type mismatch error" for Level(Temp) which is fine when on a stand alone line.
Code:
Function Level(Parent As String) As Integer
Dim Temp As Variant

Temp = DLookup("[Component]", "TestData", "[ItemNo] = '" & Parent & "'")
If IsNull(Temp) Then
MsgBox ("Found NULL")
Level = 1
Debug.Print "ItemNo Component", "Level"
Debug.Print Parent; " "; Temp; " "; Level; Chr$(13)
'Done
Else
MsgBox ("Found ItemNo")
Debug.Print "ItemNo Component", "Level"
Debug.Print Parent; " "; Temp; " "; Level; Chr$(13)

'**** This Works Fine
Level (Temp)

'**** This Doesn't Work, Why?
'Level = Level + Level(Temp)

End If

End Function
Any help would be appreciated. Thanks.

Recursive File List Function
I have a function that will return any files in a given folder. But in order to make it also return files in subfolders, i was told i would have to make it recursive. Recursive functions are something ive never had to use yet...and quite frankly i dont understand them. Could someone tell me what modifications i would have to make to this function to make it return subfolder files as well?

VB Code:
Function DirList(strDir As String) As String()    'returns a 0 based array with the files in strDir    'Can contain a pattern such as "*.*"    Dim Count As Integer    Dim sFiles() As String    Dim sFile As String        sFile = Dir$(strDir)    Count = -1    Do        Count = Count + 1        ReDim Preserve sFiles(Count)        sFiles(Count) = sFile        sFile = Dir$    Loop    DirList = sFilesEnd Function

thanks,
Nishant

Fully Kill Recursive Function
Hi all,

I have a bit of a problem with a recursive function. Basically what the function does is search for files, I used some code from an FAQ or post here on vbcity and it works very well. Below is the definition, you may know the funciton i mean from it.

Code:
Function GetAllFiles(ByVal path As String, ByVal filespec As String, _
    Optional RecurseDirs As Boolean) As Collection


Basically in my program you click a button on the main form and a dialog box pops up, with a listview and 2 buttons on it. You then choose to browse for a file (common dialog box etc...) or search for a file. The search for a file button opens another dialog box with a listview and search buttons and you type your search in and then the search begins. It prints any matching files into a listview. You then select which files you want and click another button, which adds the selected items to the first dialog box's listview. You can click OK and the dialog will close and you will see all the files you picked. This works fine.

The problem occurs when you dont wait for the search to end. There are DoEvents commands in parts of the recursive search function so the listview will show a file as it is found. This also means you can select it and add it whilst the search is still running (which is good, i want this). However you can also click ok and go back to see the files you've selected, but the search is still running. If you quit the program, it will still remain in task manager. I want the search to stop the minute OK is clicked (the only code for ok at the moment is unload me). Any ideas how you can do this, if at all?

One other thing, if I click ok whilst a search is running, and the dialog closes, and then I click search again to open the dialog back up, it will display any matches it finds as the previous search runs (ie ones that were not shown before, new ones that the halfway through search finds)

All help much appreciated

Dan

Calling A Recursive Function/sub From Itself Sends Nothing
first :thank you delcom5 for your reply.

i built a recursive function (tried calling it a sub as well - same problem)
that should builds nodes from DB to be added to a treeview.
and when i call the function from itself the node is sent as nothing (i do add byval of course).
don't have a clue why this shold happen, other parameters are sent just fine.

Recursive Function Fails To Return The Correct Value
Hi,
I'm fairly new to VB. Just tried to implement a recursive function with Tree Class. The function is as follow:

Code:
Private Function bTreeSearch(ByRef tmpx As Node, _
ByVal result As Integer, _
ByVal expr As String) As Boolean
Dim isFound As Boolean
If (tmpx Is Nothing) Then
isFound = False
Else
isFound = (tmpx.result = result)
If Not isFound Then
If result < tmpx.result Then
bTreeSearch tmpx.Left, result, expr
Else
bTreeSearch tmpx.Right, result, expr
End If
End If
End If
bTreeSearch = isFound
End Function
When I ran through debug mode, I found out that when the function found the node with the same result and set isFound = True, on the way returning to the stack, ie. back to its previous copy, where isFound is False, it returns FALSE as the value of the first copy of the function rather then TRUE value of the second copy - I hope you understand what I am talking about.

My question is, how to make this recursive function to return the TRUE value (from the second copy of the function) as the function rolls back on the stack?

(still N00b) Recursive Function Doesn't Work
Hi,

For some obscure reason an recursive function I build doesn't work:


Code:
Public Function D()
Dim TD As Integer
Dim XD As Integer

XD = 0
TD = D10
If TD = 10 Then
XD = TD + D
Else
XD = TD
End If
D = XD
End Function


D10 is a function that gives a random number between 1 and 10
What it must do is:
When D10 results in 10, then another D10 must be added:
If TD = 10 Then XD = TD + D
but for some reason VB doesn't 'step into' D and just gives the result '0'
At first I used If TD = 10 Then D = TD + D, which is shorter, but same result.

Any clue anyone?

Problem With Recursive Function To Build XML Dom Tree
I have the following recursive function

Private xmldoc As DOMDocument30

Private Sub BuildTree(ByRef parentElement As IXMLDOMElement)

Dim aElement as IXMLDOMElement

...
Set aElement = xmldoc.createElement("something")
parentElement.appendChild aElement
...
BuildTree aElement
...

End Sub

Running the code results in: "Compile error: ByRef argument type mismatch"

Could anybody help identify the problem and suggest a solution for it?

Search File In Folder An Recursive Folder With Dir Function
Hi,

I want to search ActiveX .dll in a expecific folder and in all his recursive folders.

I´ve made a recursive function using dir statement. But dir returns error when it finish in one folder and I want that dir function search in the recursive folders too.

This is my code:


Private Sub search(sFolder As String)
Dim sName As String

sName = Dir(sFolder & "", vbDirectory) ' Retrieve the first entry.
Do While sName <> "" ' Start the loop.
' Ignore the current directory and the encompassing directory.
If sName <> "." And sName <> ".." Then
' Use bitwise comparison to make sure sName is a directory.
If (GetAttr(sFolder & "" & sName) And vbDirectory) = vbDirectory Then
' sName is a directory.
Debug.Print sFolder & "" & sName ' Display entry only if it
search sFolder & "" & sName
ElseIf LCase$(Right$(sName, 3)) = "dll" Then
' sNAme is a ActiveX.dll
Debug.Print sFolder & "" & sName

End If
End If
sName = Dir ' Get next entry. <= Here happens an error when the function end searching in 1 recursive folder

Debug.Print sName
Loop

End Sub



What can I do????


Thanks and regards

Tel

Recursive Function "out Of Bounds Error"
I got that function from here but I get ann error "subscript out of range" what`s up with that ??

'recursive folder adding
Public Sub ProcessFiles(d As String)
Playlist.files.AddItem Playlist.files.ListCount + 1 & ". " & d
End Sub


Public Sub ProcessDir(strDir As String)
Dim i
Dim iCount As Integer
Dim Result As String
Dim FileList() As String
iCount = 0
Result = Dir(strDir & "*.*", vbDirectory)
Do While Result <> "" ' Start the loop.
If Result <> "." And Result <> ".." Then
iCount = iCount + 1
ReDim Preserve FileList(1 To iCount)
FileList(iCount) = strDir & "" & Result
End If
Result = Dir
Loop

For i = 1 To UBound(FileList)
If (GetAttr(FileList(i)) And vbDirectory) = vbDirectory Then
ProcessDir (FileList(i))
Else
ProcessFiles (FileList(i))
End If ' it represents a directory.
Next
End Sub

Function Needed
hey guys, anyone here have a function for returning a number between 2 given parameters etc..

Number(50,79)

would give me any randm number between 50-79

Function Needed
anyone who has the function to convert a numeric field to a string?
for instance convert "1234" to become "One Thousand Two Hundred And Thirty Four"
i need this for generating the receipts. thanx

Help Needed With A VBA/Access Function
Hi,

I have 3 functions that I need to create. They will all manipulate an Access database. The third one is a complex (at least for me) function and I haven't been able to figure it out. My VB is very rusty, maybe you can help me. Here is the description:

For each record in table "A", having the the same values for fields "Process" and "ControlName", insert in table "B" one record such as:


Code:
Table B <- Table A
ID <- The first ControlId found among the records of the group
ControlName <- ControlName
RiskId <- a list of all RiskId of the whole group of records separated by a comma.

Example:
For the combination Process="Final Statement" and ControlName="F/S", we find 16 records (in table A) with different RiskId (R1, R6, R7). Therefore we need to add the following record to table "B":


Code:
Table A
Control ID | ControlName | Process | RiskID
...
C12 | F/S | Final Statement | R1
..
C25 | F/S | Final Statement | R2
...
C38 | F/S | Final Statement | R7
...
After running the function, this is what I would have in table B:


Code:
Table B
ID | ControlName | RiskId
C12 | F/S | R1, R2, R7
Note: I am using Microsoft DAO 3.6 Object Library

That's it! Any help is appreciated!

FileCopy Function Help Needed
So far I have this

Public Sub Copy()
FileCopy(App.Path & "FileA.exe", App.Path & "FileB.exe")
End Sub

But it keep saying 'Expected '='' and I have no idea what to do.

Thanks

Jason T

VB 6.0: Delay (100) Function Needed
Searched on google, but without any succes.
I need a function where I can define how long the PC has to wait until it
executes its next command.

I know that it is possible with a timer, but that gives some complications.
A timer goes through his commands & then waits 100ms before he goes through
his commands again, but if you call sth at the end of the timer, at first
time he goes through it, he won't wait for 100ms.

I found a function on the internet (kernel function: sleep 100), but in that
case, it waited 100 mseconds BEFORE doing anything:
txtInfo.text = "before sleep"
sleep 100
txtInfo2.text = "after sleep"
--> result = that it waits 100 ms and THEN it fills the 2 textboxes, even
the one that stands above the sleep command!

I found a function delay(100) in a dll: port.dll: that is to control the lpt
port, but that dll only works in win98, not in NT or XP. When I use the
function out of that dll, the PC hangs a while & I don't think any code is
executed then...


If anyone knows any command like I need, it would be wonderfull!
I need to write several data to the lpt port & after each command and data
send, has to wait 100ms, so I have to call that function more than once on
different places...

Big thanks in advance!

ExtractAll Function Needed
I need an extractall.

So I can do this:


Code:
Dim strToExtract As String
strToExtract = "a0ba1ba2ba3b"


Then I can call:
ExtractAll strToExtract, "a", "b", List1

Then it will add 0,1,2,3 to List1

IsServerOS Function Needed!
hi - i need a function that returns true if the user is using a windows server OS

thanks in advance
Kris Bennett

Listbox - A Function Needed
If I have a listbox with the list of numbers
ex1. 1, 3, 4, 5, 7...
ex2. 3, 4, 7, 9...

How do I find out the smallest number that is missing with a function?

ans:
ex1. 2
ex2. 1

Code Of MOD Function Needed.
VB Code:
Dim a As Variant    Dim dummy As String    dummy = "7001480882"    a = dummy Mod 97


I've tried this but i get an overflow error on the function.
The mod function wants a long , and I am way over it.

Does anyone know how the syntax is from this function so i can rewrite it for usage without errors.

I am not sure it will work though cause the following line gives the same overflow error

VB Code:
Dim a As Variant  Dim dummy As String  dummy = "7001480882"  a = dummy i


Meanwhile I continue my search

Advanced thanks

MsgBox Function Help Needed
Hi Guys,
I am very new at this so please excuse me... I am trying to write code for an Access database that will create a directory and a MSWord file from an Access form via a command button. So far, so good. By clicking on the button the directory and file are created. NOW I need to have the program check to see if the file already exists before creating it. I want the program to check for the file, and if it is present, prompt the user with a message box that asks if the file needs to be re-created. If the user clicks yes, proceed; if the user clicks no, the code should stop. I can get the message boxes to come up depending on whether the file is created or not, but I can't get the part where the yes and no buttons appear and the program takes action depending on the button clicked. I just can't seem to get this right. Here is what I have so far. The "Response" part is wrong but I can't figure out how else to do it.

Dim FileInQuestion As String
Dim tmp As String
tmp = "C:" & Trim(CStr(Forms!Foreclosure!MJUNumber)) & "" & Trim(CStr(Forms!Foreclosure!MJUNumber)) & "merge.doc"
FileInQuestion = Dir(tmp)
If FileInQuestion <> "" Then
Call MsgBox("This file has already been created! Create new file?", vbYesNo + vbDefaultButton1 + vbApplicationModal + vbMsgBoxSetForeground, "File Exists!")
If Response = "Yes" Then
Resume Next
Else
GoTo EndSub
End If

Deletsetting Function Help Needed
Going by Microsoft MSDN (unless I read it wrong) I should beable to remove a key that was made by savesettings. but for some reason I cant remove it. Any help would be great. Here is a snip of code I am using.

Code:
Private Sub CmdRemoveLink_Click()
Dim x As Integer
Dim Remove As String
Dim Gone As String

For x = 0 To List1.ListCount - 1
     Select Case List1.Selected(x)
          Case True
               Gone = Split(List1.Text, " ", 15, vbTextCompare)(0)
               Remove = GetSetting(Prog, "Web Sites", Gone)
               'MsgBox Remove
               
               DeleteSetting Prog, Gone, Remove '<<<<< Help Here please
               
    WebAddressCounter = GetSetting(Prog, "Web Sites Counter", "Counter", 1000)
               SaveSetting Prog, "Web Sites Counter", "Counter", WebAddressCounter - 1
          End Select
Next x

List1.Clear
         
AllSettings = GetAllSettings(Prog, "Web Sites")
For intSettings = LBound(AllSettings, 1) To UBound(AllSettings, 1)
     Short = AllSettings(intSettings, 0)
     Url = AllSettings(intSettings, 1)
          If Len(Short) < 15 Then
               tShort = 15 - Len(Short)
          End If
     List1.AddItem Short & String$(tShort, " ") & vbTab & vbTab & Url
Next intSettings
Lbtotal.Caption = "Total Sites = " & List1.ListCount

End Sub

If I can not use deletesettings is there an API I can use to do this?
Any help would be great.

Help Needed With SavePicture Function Over VB PictureBox.
Hello!

I'm facing a strange problem with the simplest method of saving PictureBox Picture. Actually, I'm working on an application in which I read the RGB values from a tab delimited Text file. What I need to do is ... create 20 by 20 single colour square BMP files from these RGB colour data extracted by parsing Tab delimited text file. So, I split the file with vbTab as delimited and then parse each line with split function and , as delimiter. This way, I get the RGB values.

After this step, I set PictureBox.Backcolor = RGB(R,G,B). After this steps, firstly I tried directly saving it as SavePicture PictureBox.Picture; but this did not work; so I implement ...

PictureBox.Backcolor = RGB(R,G,B)
PictureBox.Refresh
PictureBox.Picture = PictureBox.Image
SavePicture PictureBox.Picture

I run this in a For Loop When this code is executed; though the R, G and B are changing, all the resulting BMPs show same colour. What can be the problem? Please help me in solving this issue.

As I mentioned above, basically I want to create a 20 by 20 BMP image from given R, G and B values. Is there any other reliable method of doing it? Please let me know or else suggest me some way-out for the solution I'm trying to implement.

Eagerly waiting for your reply ...

Regards,

Ruturaj.

Command Function / Registry Help Needed
The purpose of my application is to batch process files.
The plan is, using windows explorer you would select all the files you want to process, then right click, select my "do job" menu item and then each of these files would be processed by my app.

I have written my app and it works fine.
I have added an entry to the registry that gives me the menu item when I right click files of a particular type. This registry entry looks similar to c:project1.exe "%1"

All works well, as long as I process only 1 file.
As soon as I do a multiselect it's as if nothing happens.

I would have thought that the command function would have returned all files selected if my app had been called but perhaps I am wrong.
Does anyone know if Windows works this way?
eg Would windows call one instance of my program with many command line arguments, or would it be many instances of my program, each with one file as an argument.

Because my app doesnt seem to be being called, I suspect that I need another registry entry added somewhere for multiple file selections but I have searched and cant find any information on this.

If anyone can shed any light on this problem for me I would be greatfull.

Thanks in advance

Greg

Quick Math Function Needed
Hello...
I just need a quick and fast way to determine if a number is a whole number (without decimals!)...

Easy Rounding Function Needed
Hey all.. dont have much time to work this one out.. i need a function that will take a whole number and always round it up to the next thousand.. so if you pass it 400, it returns 1000, if you pass it 1001 it returns 2000.

I could easily write this with a bunch of IF or select case statements.. but the function needs to be unlimited (with reason).. anyone have a simple number manipulation technique to do this?

thanks,
-mcd

VB6 + Access97, Search Function Is Needed.
Hi all!

I can't say that i'm an advanced VB6 programmer, so I need some help.

I have a VB6 application that connects to a access 97 database, my company uses this for bugreporting on one of it's software applications. Let's call the software FRP.

I can add new entries to the database with my application, everything works just fine. But now i want to add a function where the you can search among the entries. So that the companys helpdesk can search it before calling me on technical advice regarding the FRP. How do I do this?
A really nice thing would be to be able to search the database and get the contents of the first match in a form, with every field in the database put in a textbox in the VB6 form. And if that not is what you are searching for be able to press a 'continue search' button to start searching from the entry you have passed to the VB form. Getting it? :) Okey, how do write some search code that will do that? I'm using VB6 Enteprise Edition with Access97 and i connect throug the Opendatabase and OpenRecordset thingy.

And again, _PLEASE_ be specific, I'm a novice.
And yes, I HAVE searched this fourm without any success!

Thanks in advance!
/A novice programmer from Sweden.

Guru Needed - Convert C To VB Function
Never done this before can this be converted to a VB6 function?

Code:
class Win32_NetworkAdapterConfiguration : CIM_Setting
{
  boolean ArpAlwaysSourceRoute;
  boolean ArpUseEtherSNAP;
  string Caption;
  string DatabasePath;
  boolean DeadGWDetectEnabled;
  string DefaultIPGateway[];
  uint8 DefaultTOS;
  uint8 DefaultTTL;
  string Description;
  boolean DHCPEnabled;
  datetime DHCPLeaseExpires;
  datetime DHCPLeaseObtained;
  string DHCPServer;
  string DNSDomain;
  string DNSDomainSuffixSearchOrder[];
  boolean DNSEnabledForWINSResolution;
  string DNSHostName;
  string DNSServerSearchOrder[];
  boolean DomainDNSRegistrationEnabled;
  uint32 ForwardBufferMemory;
  boolean FullDNSRegistrationEnabled;
  uint16 GatewayCostMetric[];
  uint8 IGMPLevel;
  uint32 Index;
  uint32 InterfaceIndex;
  string IPAddress[];
  uint32 IPConnectionMetric;
  boolean IPEnabled;
  boolean IPFilterSecurityEnabled;
  boolean IPPortSecurityEnabled;
  string IPSecPermitIPProtocols[];
  string IPSecPermitTCPPorts[];
  string IPSecPermitUDPPorts[];
  string IPSubnet[];
  boolean IPUseZeroBroadcast;
  string IPXAddress;
  boolean IPXEnabled;
  uint32 IPXFrameType[];
  uint32 IPXMediaType;
  string IPXNetworkNumber[];
  string IPXVirtualNetNumber;
  uint32 KeepAliveInterval;
  uint32 KeepAliveTime;
  string MACAddress;
  uint32 MTU;
  uint32 NumForwardPackets;
  boolean PMTUBHDetectEnabled;
  boolean PMTUDiscoveryEnabled;
  string ServiceName;
  string SettingID;
  uint32 TcpipNetbiosOptions;
  uint32 TcpMaxConnectRetransmissions;
  uint32 TcpMaxDataRetransmissions;
  uint32 TcpNumConnections;
  boolean TcpUseRFC1122UrgentPointer;
  uint16 TcpWindowSize;
  boolean WINSEnableLMHostsLookup;
  string WINSHostLookupFile;
  string WINSPrimaryServer;
  string WINSScopeID;
  string WINSSecondaryServer;
};



if so how can it be done?

Thanks

Help Needed Please In Writting A Boolean Function In VBA?
I wanted to know how to write a Boolean function in vba, that checks all the records of two fields in a form. The Function should return true if all the Football result is Win and false if any of the football result is lose

Zub

<Edit> Lankymart - Moved from VB & Databases to more relevant forum. </Edit>



Edited by - lankymart on 9/20/2007 9:35:52 AM

Excel Search Function Needed
I have a database of contacts in excel. I am trying to write a search function that will take in a search string from an input box, find the ROWS containing the search criteria and copy those rows to another worksheet in the same workbook. I found some similar code that puts links to the "found" cells on a new worksheet. But I would rather have the entire row copied over. This is the code I was working off of:


Public Sub vbaQuickFind()
    'Object variables
    Dim wks As Excel.Worksheet
    Dim rCell As Excel.Range
     
     
    Dim szFirst As String
     
     '{i} will act as our counter
    Dim i As Long
     
     
     
     'bTag is our switch to determine if we highlight cells or not
     'Initially set to true
    Dim bTag As Boolean
    bTag = True
     
     
     
     'Use an input box to type in the search criteria
    Dim szLookupVal As String
    szLookupVal = InputBox("What are you searching for", "Search-Box", "")
     
     
     
     'if we don't have anything entered, then exit the procedure
    If szLookupVal = "" Then Exit Sub
     
     
     
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
     
     
     
    '=============================================================
    'Add the sheet for linking {Check for existence first}
    'if it exists, get rid of it
    For Each wks In ActiveWorkbook.Worksheets
        If wks.Name = "Found it here" Then
            wks.Delete
        End If
    Next wks
     
     
    'Add the sheet
    Sheets.Add ActiveSheet
     
     
    'Re-name the sheet
    ActiveSheet.Name = "Found it here"
     
     
    'Add a heading to the sheet with the specified search value
    With Cells(1, 1)
        .Value = "Found " & szLookupVal & " in the cells below:"
        .EntireColumn.AutoFit
        .HorizontalAlignment = xlCenter
    End With
    '=============================================================
     
     
    'Reselect the previous sheet
    ActiveSheet.Next.Select
     
     
     
     '=============================================================
     'Prompt if you want to shade occurences in the cells
     '*Highlighted cells will need to be manually removed*
    If MsgBox("Would you like to highlight all found occurences also?", vbYesNo, _
    "Highlight Cells") = vbNo Then
         
         
        'If shaded cells are not called for, set out boolean switch to FALSE
        bTag = False
         
    End If
    '=============================================================
     
     
     
    i = 2
    'Begin looping:
    'We are checking all the Worksheets in the Workbook
    For Each wks In ActiveWorkbook.Worksheets
         
         
        'We are checking all cells, we don't need the SpecialCells method
        'the Find method is fast enough
        With wks.Cells
             
             
            'Using the find method is faster:
            'Here we are checking for cells that only have {szLookupVal} explicitly
            'We are not matching case, so if it's a word, it can be {Hello, hello, HELLO}
            'The optional Find properties can be modified to adjust to different kinds of searches
            'Like finding a cell with a text string that contains part of a word, or has the word
            'contained somewhere within the text string
            Set rCell = .Find(szLookupVal, , , xlWhole, xlByColumns, xlNext, False)
             
             
            'If something is found, then we keep going
            If Not rCell Is Nothing Then
                 
                 
                'Store the first address
                szFirst = rCell.Address
                 
                 
                Do
                     
                    'Link to each cell with an occurence of {szLookupVal}
                    rCell.Hyperlinks.Add Sheets("Found it here").Cells(i, 1), "", "'" & wks.Name & "'!" & rCell.Address
                     
                     
                    'We check our boolean trigger value, and decide if we are coloring cells
                    'or are we just adding links
                    Select Case bTag
                         
                    Case True
                         
                        rCell.Interior.ColorIndex = 19
                         
                    End Select
                     
                    Set rCell = .FindNext(rCell)
                     
                    i = i + 1 'Increment our counter
                     
                Loop While Not rCell Is Nothing And rCell.Address <> szFirst
                 
                 
            End If
             
        End With
         
    Next wks
     
     
    'Explicitly clear memory
    Set rCell = Nothing
     
     
    'If no matches were found, let the user know
    'and remove the link sheet
    If i = 2 Then
        MsgBox "The value {" & szLookupVal & "} was not found on any sheet", 64, "No Matches"
        Sheets("Found It Here").Delete
    End If
     
     
    'Reset application settings
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub


My VB skills are not sufficient enough to complete this task. Hopefully someone out there can help me. Thanks.

Jonathan

Alphabetic Increment Function Needed
I want to increment a string with the value of "A" sequentially. When it reaches "Z", I would like to start over with the value of "AA" - Something like this
Code:
A
B
C
(continue through the alphabet)
X
Y
Z
AA
AB
AC


I just can't seem to hit the right algorithm. Anyone have any suggestions?

Function For External Data Import Needed -- VBA
Hi all. I have recently been trying to update some logfiles that are commonly used to track data for how much work is processed in a given work area. At present, I have the data writing out to two separate CSV files, which will be feeding into two separate types of reports. What I really need to do now is to make it easy for the processors to get their production data simply by choosing their name and the date they need production data for. I have the form designed and correctly producing the filename string that I will need for importing the data, but the Workbooks.OpenText references that I have seen here are not what I want, because they open the CSV file in another workbook, which doesn't utilize the template that I actually have set up, which will "interpret" the data and give the end results to the requestor (which is all they will need at the end of their day). Few of the users will easily understand how to import the data manually; hence my inquiry here. Is there any easy way to accomplish this? I need to have this completed in about 8 hours, and I haven't slept yet, so the clock is ticking away. Any suggestions on what I need to do to accomplish this? I apologize if this is something simple that I am overlooking, but I have had to teach myself by experience (trial and error) most of the VBA that I know.

Thanks,



PB

11-01-2005 For Loop - Function Argument Help Needed?
Hi,

I'm am struggling to incorporate a function as an argument into a function. Easier to demonstrate with the problem itself.

Dataset:
"Trade ID's"
1) A126271
2) A129037
3) A145850
4) A145856
5) A146454
6) A146455
7) A147630
8) A147637
9) A175585

The Procedure I have is:

Sub xtestfunc()

Dim lngItem2 As Long

Debug.Print NewHDETest(Worksheets("BespokeList").Range("C3"), "A126271".Contains("AA.SENIOR UNSECURED") '3

End Sub

Quick Background:
The above procedure when run calls a function called NewHDETest which looks for the Trade ID "A126271" (as stated in the function argument above) in a very long list of 300 entries. Once found it offsets a column and grabs the contents of the ID which is a string containing 123 entries delimited by a comma. It then checks the 123 entries to see whether "AA.SENIOR UNSECURED" is contained within the string and declares either true or false.

Problem:
At the moment the user has to manually type in the Trade ID (e.g. A126271) into the argument of the function above, but since the dataset at the top contains 9 Trade ID's, I want a function that can automatically add different Trade ID's to the argument from a dataset contained within an excel spreadsheet. And when the procedure will execute it will perform the same task for every trade ID and return either true or false values.

For example:
For Trade ID No.1 = A126271

Therefore function will be:
Debug.Print NewHDETest(Worksheets("BespokeList").Range("C3"), "A126271".Contains("AA.SENIOR UNSECURED") '3

Output: True or False (i.e. does the Trade ID contain the string or not?)

After Trade ID No.1 (i.e. A126271) the argument will change to Trade ID No.2 (i.e. A129037) and perform the same function. And then when that is completed it will then perform the same function on Trade ID No.3 (i.e. A145850) and so on until all 9 Trade ID's are completed.

Can someone please help me with this?

Thanks

Muj

Slight Help Needed With Recordset Function[CLOSED]
Ok i was having a problem with the data control function so i decided to change it and write the code for it instead..
ive the code write and its like 85% working lol..
all the data comes up but all that isnt working is the next and previous buttons on my form.. wen i click them it isnt going through and showing each record properly..

i have a msgbox appearing when the last record in the database is got to and same for the start aswell and wen clickin the next button it does get till the msgboxes so its sort of partially working if that makes sense.. heres my code.. i need the information to appear each time the next and previous buttons are pressed just as it would using a data control...
thanks...


VB Code:
Option ExplicitDim dbPS2 As Database Dim rsManuDetails As Recordset Private Sub Form_Activate()Set rsManuDetails = dbPS2.OpenRecordset("Manufac Details", dbOpenTable) End Sub Private Sub Form_Load()    Set dbPS2 = OpenDatabase("PS2.mdb")     Set rsManuDetails = dbPS2.OpenRecordset("Manufac Details", dbOpenTable)     txtManu = rsManuDetails.Fields("Manufacturer").Value    txtPublisher = rsManuDetails.Fields("Publisher").Value    txtAddress = rsManuDetails.Fields("Address").Value    txtNumber = rsManuDetails.Fields("Tel No").Value    txtEmail = rsManuDetails.Fields("Email").Value    txtWeb = rsManuDetails.Fields("WebAddress").ValueEnd Sub Private Sub cmdNext_Click()    ' Set current record to the NEXT record in the current index sequence    rsManuDetails.MoveNext     ' Test for end of file    If rsManuDetails.EOF Then        ' Inform user & move to last record        MsgBox "No more records", vbOKOnly, "End of File"        rsManuDetails.MoveLast    End IfEnd Sub Private Sub cmdPrevious_Click()' Set current record to the PREVIOUS record in the current index sequence    rsManuDetails.MovePrevious        ' Test for beginning of file    If rsManuDetails.BOF Then        ' Inform user & move to first record        MsgBox "No more records", vbOKOnly, "Beginning of File"        rsManuDetails.MoveFirst    End IfEnd Sub


thanks for any help..it will be greatly appreciated

#Using Sendkeys Function † [Simple && Quick Help Needed]# † Thx †
Hi Ive been using the Sendkeys function from sometime. Its real good but i want to take it to a bit higher level. It basically sends keys to The Active Window. Is there anyway i can make it set a connection with a textbox on some other application like notepad or msn... and then even if that application is not active all keys are sent to that same textbox?

there is some way to do is... coz ive seen it in some programs. Any idea how is that done?

Pls help,
Thx

Macro Help Needed Using Offset And Index Function
i have a column A ....in which I have years ....like 2001 ....2002...2003.....2004....12 times each as there are 12 months.....
now..in column B i have perf rtns....say 1% 2 % 3 % etc etc ...

now i want to see how much was the perf in 2001....so i shud use....= product( 1+ range ( all data for 2001 ) -1 array formula.....to get cumulative formula....

this can be done by a productif formula.....which i dont know how to do ...like sumif...or countif.....

pls help me with a macro which will do this.....

Dsum Function Lotus To Excel Conversion Needed
Hi all

I am having a major problem at the moment.
We have files in lotus and a transferring them into excel
all was going grand with changing the formula until Dsum popped up
I cannot seem to get the formula to work in excel and was wondering if any lotus or excel guru out there could lend me a hand

@DSUM($MAINDATA,"Q",MO=$B17#AND#YE=D$4#AND#MON=D$3#AND#MB=$A17)
How do convert (edit) this formula so I can get the same results in Excel??
I am having trouble finding out how to use the dsum for multiple criteria in excel.
Any help would be great
Thank you.

Function Needed To Find The Length Of A Curved Line.
I need a function to calculate the length of a curved line based on width and depth. Any ideas?

#Some Help With Replace() Text Function Code#...[Simple Help Needed]
im tryin to make the replace text function... for my notepad. In the replace form when the user clicks on Replace button the search text's first appearance is found and is replaced with the new text. So the user clicks replace once to replace the text once in the textbox just like the replace function in notepad. Here is my code....


Code:
Option Explicit
Dim strText As String 'Text To Search and Replace within
Dim strFindText As String 'string to replace
Dim strReplaceText As String 'text to replace with
Dim bWWCheck As Boolean ' Check for wordwrap

Private Sub Form_Load()
'*******FORM LOAD ONLY CHECKS FOR WORDWRAP******
If frmNote.txtDataFieldWW.Visible = True Then 'Check whether wordwrap is true or false
strText = frmNote.txtDataFieldWW.Text 'value from wordwrap textbox
bWWCheck = True
Else
strText = frmNote.txtDataField.Text 'value from non-wordwrap textbox
bWWCheck = False
End If
End Sub


Private Sub cmdReplace_Click()
strReplaceText = txtReplaceText.Text


If cbMatchCase.Value = 1 Then 'Check for case-sensitive
strText = strText 'dont change case
strFindText = txtFindText.Text 'dont change case
Else
strText = LCase(strText) 'change to lcase
strFindText = LCase(txtFindText.Text) 'change to lcase
End If

Dim myPos As Integer 'Position where last stopped

If InStr(strText, strFindText) Then
myPos = InStr(strText, strFindText)
strText = Left(strText, myPos - 1) & Replace(strText, strFindText, strReplaceText, myPos, 1)
frmNote.txtDataField.Text = strText
End If

End Sub
Problem:
When the case sensitive is on it all works fine.... i have no problem with it...
But when case sensitive is off.. wat happens is
strText = LCase(strText) 'change to lcase
strFindText = LCase(txtFindText.Text) 'change to lcase
the main text and the text to search for both become to lowercase...

and after the replace function....
frmNote.txtDataField.Text = strText 'Where the whole string is lowercase...

thus all that was typed before in uppercase also now becomes lowercase.. coz the first thing that is done when the user clicks the button is to check whether it shud be case sensitive.. and if it is true it converts strText and strFindText to lcase... and then txtDataField.text=strText <<< which is completely lowercase.

IS there a way that it can replace text w/o case sensitivity and a way to avoid my whole text from becoming lowercase?

I found it hard to convey my problem! Hope u understood
Thx in advance,
Pls help

Copyright © 2005-08 www.BigResource.com, All rights reserved