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




Returning A String


Ok here we go, i wasent gonna ask this but it looks like i have to. Its kinda hard to describe so i am gonna show you some coding. What i am doing is let me give you a easier explenation then the hard one

I am lets say validating something that's typed into a textbox, so when the text is entered it has to be a specific way. So i have a function called lets say


Private Function ValidName(fGet as String) as Boolean

so that basically means when i call that function i would call it like this from my command button

if ValidName(fget) = true then

so what i am saying is if the name is valid do the following. but the problem that i have now is the function that i have has to be like this


Private Function ValidType(fGet as String) as String

now i have to return a string. my question is how do i call that and so i will return the string ? sorry if i didnt explain it good enough. But i need this by tomorow, the assignment is due buy last class tomorow , couldnt buy the book yet so i have to ask you , sorry but i am buying the book in 2 days, getting my dam check finally . Thanks for the help.




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Returning A String From A VB6 Std DLL
I have created a standard (not ActiveX) DLL from VB6 and am trying to return a string to the calling application from the DLL function. The problem is that the string returned is in wide character format (nulls in between characters)...is it possible to return it in narrow character format (no inter-character nulls)?

[SQL] Returning Information As String
Hi there!

I've been working on this all day so far. It is the login information for my program, where the user inputs his/her username and password, and the program will connect to the database and check to see if the username and password match a record in the database.

Here's what I have so far.


Code:
Option Explicit
Public conn As New ADODB.Connection 'Connection to be used to mysql database

Public Function OpenConn(srvIP As String, dbNAme As String, dbUser As String, dbPass As String, dbPORT As Long, statusbox As StatusBar)
On Error GoTo errH

If conn.State <> 0 Then conn.Close 'Check if currently connected if yes, disconnect.

conn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=" & srvIP & ";DATABASE=" & dbNAme & ";" _
& "UID=" & dbUser & ";PWD=" & dbPass & "; PORT=" & dbPORT & "; OPTION=3"
conn.Open 'open the connection

Exit Function
errH:
statusbox.SimpleText = "Could not connect to server..."

End Function

Private Sub cmdLogIn_Click()

sb.SimpleText = "Connecting to server..."

OpenConn "98.XXX.X.XX", "databasename", "databaseloginusername", "dbpassword", "3306", sb
I don't know how to have it look up the txtusername.Text and txtpassword.Text fields in the database though. I get the connection, but I don't know the rest!

Is there a way to simply query for these two items and if it returns true, change the sb.SimpleText to "Log in details verified!"?

Returning String From VB To Access
I will try to explain my problem better this time!

I have a form in MS Access, when the user moves into the MODEL # field of the form, an ON FOCUS event launches a VB app. This app guides the user through multiple lists, allowing one choice per list and building a model # from the choices.

Once all the choices have been made and the model # is built, how can I return the resulting model # to the MS Access field?

Thanks

Returning The Length Of A String?
Sounds simple and I'm sure it's really easy, I just don't know what command I can use.

Returning A Character At A Specified Position In A String
What is the way to do this? I tried using GetChar() but that didn't work...

Returning The Full Length Of A String
say i use this as my data

"hello there, how you doing?"

i would use split(sdata, " ")(3)

that would return "you"

how could i get it to return the rest of the line like "you doing"

cheers

Searching String Returning Incorrect Results...
im using this code to search through an HTML file:

Code:
tempstr = WebBrowser1.Document.documentElement.innerHTML
tempstr = Right$(tempstr, InStr(tempstr, "Andy:"))
Text1 = tempstr

but for some reason it is returning the string about 200 chars infront of the string i searched for...
Any ideas of why this is happening, and how i can fix it?

Inet Returning Non-string....wth Kind Of Type Is It????
so i got a thing like this...


Code:
dim RecievedData as string
dim YourYahooUserName as string
dim YourYahooPassword as string
RecievedData = Inet1.OpenURL(http://edit.yahoo.com/config/login?.src=bl&login=" & YourYahooUserNameHere & "&passwd=" & YourYahooPassword)


now funny thing here...when i input the WRONG id/pw ... i get the right data....u know saying i got the wrong id/pw .... but if i input correct id/pw i get an error saying wrong type...i just want to know whhyyy....btw if ur wondering wth this is...its for getting the yahoo cookie....

AcE

Function Returning A String From A Text File
dear gurus

i want to write a function (in plain VB 6) which would take a filename as input and return me a string which is stored in the text file. The text file contains only one string. Also please tell me how do i use this function in the calling program.

thanks


 

Edited by - saeedakhtar on 2/10/2008 12:03:17 AM

Exchange Server Returning Strange Address String
I work on developing a system in VB. We use an Exchange server as mail system, and every time an email is sent within the LAN, the senders email address comes up something like this: EX:/0=ACOS AS/OU=FIRST ADMINISTRATIVE GROUP.

As we would like to send a reply to the sender, I am looking for a way to get a hold of the readable address.

Recordset Only Returning Five Records When It Should Be Returning 466
All,

Doing this in excel with VBA. Haven't working in VBA for a very long time but can't see why I'm getting these results.

I run this sql in query analizer and I get 466 records back but when the same sql runs in vba I only get five records back. I checked the conn string to make sure I was running against the correct db. Is it that I'm not setting up my recordset object correctly?

Code:
Set conSql = New ADODB.Connection
    conSql.Provider = "SQLOLEDB"
    conSql.ConnectionString = "Data Source = Test1;" & "User ID=sa;Password=test; Initial Catalog = test;"
    'conSql.ConnectionTimeout = 120
    conSql.Open
    
    Dim strSql As String
    Dim fldField As ADODB.Field
    Dim docXML As New MSXML2.DOMDocument
    Set rstData = New ADODB.Recordset
    
    strSql = "SELECT CedingCoID, effectivedate, XMLString " & _
                "FROM CAPSProgram " & _
                "Where ID > 1 and CedingCoID > 1" _
          ' "WHERE (CedingCoID = '" & intCedingCoID & "' AND EffectiveDate = '" & CDate(datEffectiveDate) & "' AND Description " & IIf(strDescription = vbNullString, "IS NULL)", " = '" & strDescription & "')")

    rstData.Open strSql, conSql, adOpenForwardOnly, adLockReadOnly
    'Set rstData = conSql.Execute(strSql)
    Do Until rstData.EOF
       ' If Not rstData.EOF Then
            globEffectiveDate = rstData.Fields("effectivedate").Value 'set global effective date for future use
            docXML.LoadXML (rstData.Fields("XMLString").Value) 'load glabal xmldoc for all load routines
            globCedingCoID = rstData.Fields("CedingCoID").Value
              Call LoadCapsProgram(docXML)
            Call LoadCapsLossHisEvents(docXML)
            
            
        'End If
      rstData.MoveNext
    Loop
    

Returning Value
I'm using the following command to make a sum from a range of cells.


Code:
Dim Pa As Integer
ActiveCell.Offset(1, 5) = WorksheetFunction.Sum(Sheets("BOMA").Range("F5", Sheets("BOMA").Cells(Range("F65536").End(xlUp).Row + 1, 6)))
Pa = ActiveCell.Offset(1, 5)

The program return an error and stops at Pa = ....
Debug shows that Pa = 0 even though the sum in this cell are something else.

Some ideas

Returning From A Sub
Can any one tell me is there a way to return from a sub function
such as:
sub Replace()
blablabla
end sub

is there a way to return to the place in another function where I called this sub from?
if not is there another way I can run the same procuder and come back to my starting point?

Returning A Value From A Sub?
well I have something along the lines of

VB Code:
public sub returnTest(theNum As integer)if theNum = 1 then'return something elseend ifexit sub

But, I don't know how to return something in vb.
I would like to use this sub like..

VB Code:
testVar = returnTest(1)

Returning A Value From An Exe
Hello,

I am trying to make an exe which returns a value to the command prompt when run through the command line. I am using cmd line parameters..

Thanks
Ajit

Mts, Vb6, W2k, Not Returning
It's only been a week and it's time for me to throw this out to bigger brains then mine.

I have a vb6 app that uses MTS objects to retrieve data and do other nifty db stuff. When it was on nt4 I wrote a report engine that used MTS and generated a html report for the user. Dam* users now want me to implement it on w2k.

I register the dll in component services, run the control on the client that calls it:


VB Code:
Set obj = CreateObject("RDS.DataSpace")  Set report = obj.CreateObject("DCISReportEngine.Report", sServer)  'Set report = obj.CreateObject("DCISReportEngine.Report", "localhost")         'should return report url                strURL = report.GenerateReport(Conn, sServer, sSQL, sRepDef, boolDup, boolGroup)


Now running locally it runs fine. But when the code above runs it creates the object (starts the package running on the server) but
returns a null string. It should return a string with a url in it.

So I ask what am I not getting? I added a log file to the MTS dll and it doesn't create the log so I'd guess it doesn't run.

But nothing tells me that it doesn't.

Suggestions? Mine regarding giving back my nt4 have gone unanswered.

Thanks for your time,
Dave

Returning Value From Exe
Hi,

Thanks for reading. I want a VB exe which should return a value say some success or failure regarding the operation happening inside it. Just like a C++ program returning a value to the console. And I want my java program to read this. How can I return the value from my VB program?


Thnx,
Pres.

I Really Don't Know (returning A Value)
My problem is kinda complicated. I have made my own msgbox because the normal msgbox freezes my program and that's not good. But now I can call the function. This opens a form and if it's already openend it put's the info into a type MSGINFO. So far so good. That form raises an event to tell if a button got clicked. Now when that happends I want to return the value to where the sub got called. And that's not possible (I think). But I don't want the sub wich calls the msgbox form to use something like:

DO
DOEVENTS
LOOP until Clicked

and then save in the boolean clicked if it got clicked cause that uses to much resources and gives up to much time. It's kinda complicated but I hope someone has got an answer.

Why Is It Returning Nothing?!?!?
I have this code piece to try and convert a month in numbers to the actual month like 11/ would be november. But I get a blank msgbox when I try this code and I can not figure out why! thanks for any help!

Dim strdate As String
Dim strmonth As String
Dim theday As String
Dim str2 As String
Dim strday As String
Dim chkmonth As String

strdate = Text1.Text

If Left$(strdate, 3) = "/" Then
Select Case Mid(Text1.Text, 1, 2)
Case "10"
str2 = "October"
Case "11"
str2 = "November"
Case "12"
str2 = "December"
End Select
strmonth = str2
End If
MsgBox strmonth

API Returning Nothing
I got a few problems...
What do you do when you use a GetText Function to get the text on a window and nothing comes back? Like you know for a fact your code is right and bug free. I thinking the window has something blocking API or something. Some windows and objects dont let you use API on them is that possible? Some windows/objects you can't hide. Like Ad bars that dock on ur computer and stuff. How can you hide em? Also I know of one window i have you can SEE it has a title bar and a caption in it, but an API spy can get it's caption.
- How do you get around all of this? -
- How can I hide the windows i want to hide, and get text from objects that have text in em like a text box or maybe password box, or even a label, and captions? -
Maybe theres something I would use instad of API??
Please help...

My GetText Function:

Code:
Public Function GetText(WindowHandle As Long) As String
Dim TheText As String, TL As Long
TL = SendMessageLong(WindowHandle, WM_GETTEXTLENGTH, 0&, 0&)
TheText = String(TL + 1, " ")
Call SendMessageByString(WindowHandle, WM_GETTEXT, TL + 1, TheText)
TheText = Left(TheText, TL)
GetText$ = TheText
End Function

Returning A Value
So I'm working on my gradebook programme. As mentioned in other posts I'm a teacher though not of computers - that's just a hobby.
I have a form with 5 textboxes in an array txtMark(0), txtMark(1) etc.
Each one contains a mark for a quiz. Now, if a student is missing a mark due to absence or something I want to recalculate the average based on the number of marks available. If there are only 4 marks then the divisor for that average should be 4.

Here is my code for the command button to calculate the average

Private Sub cmdAverage_Click()
intDivisor = txtMark().Count 'sets the divisor to the same number as there are textboxes
ReCalc (intDivisor)
Dim i As Integer

intTotal = Val(txtMark(0).Text) + Val(txtMark(1).Text) + Val(txtMark(2)) + Val(txtMark(3)) + Val(txtMark(4))
 'I know that line is clumsy - I'll tidy it up later
txtAverage = CInt(intTotal / intDivisor)
End Sub

I also have a function ReCalc which is supposed to iterate through the text boxes and if any of them are empty, the divisor should be reduced accordingly:

Public Function ReCalc(intDivisor) As Integer
Dim i As Integer
Dim ctr As Integer
ctr = 0
Dim ctl As Control
For Each ctl In Controls
    If TypeOf ctl Is TextBox Then
        If ctl.Text = "" Then
            ctr = ctr + 1 ' supposed to count how many text boxes are empty
            intDivisor = intDivisor - ctr 'supposed to reduce the divisor by the number of textboxes that are empty
        End If
    End If
Next ctl

End Function

Unfortunately it just doesn't work. intTotal is always divided by 5 regardless of how many textboxes contain text. I'm not getting any errors so it must be a logic error but I can't see it. Any help?

Thanks For Returning...
Hi,

I juz like to thank the adminstrators of this discussion board...I had so many questions regarding vb programming during the time the board was not functioning and felt so helpless... I took a long time to figure out how to solve problems compared to when I can juz pose the questions to ppl who help out with answering of questions on this board.

Juz to show my gratitude
Adrel

Returning Mouse Down
Hey, I'm making a game and I have a bunch of Shapes on my form. When a user clicks on one of the shapes I would like it to return which shape it is so I can add a color to the shape that is clicked.

Example:

o o o o o <----Shapes (In an array 0-4) called shapePeg

^ ^ ^ ^ ^ <----Colored Shapes named shpRed, shpYellow, shpBlue, shp Green shpOrange

now say the user clicks on the shapePeg(2) shape, I want it to return that shape so that when the user clicks on one of the color shapes, the color will then go into the shapePeg(2)

I hope it isn't to confusing.

Help Returning Line Set?
Hi, i have the following problem.


I have a 6 multine textboxes not linked to eachother in any way, EXCEPT.. that they contain information wich is related to eachother..

like this :

Code:

text1: text2: text3: etc

info1 info2 info3
info1 info2 info3
info1 info2 info3
info1 info2 info3
as you can see, the first line of text1 .. contains information relevant to the same line in text2/text3/text4/text5/text6.
if you still dont understand 1 more example :

say we have a chair.. and we put it in a table.


Code:

colour type serial

blue antique 123-3472
red old-style 234-4567
now i want those information bits to be linked to eachother by counting the lines on wich they exist.

say i would want to see what would exist on lines 100~200

so therefor i would need it to do this :

1. Count the lines in text1 , start reading from line 100 .. and stop at line 200
2. print those in any way ( im going to write them to a textfile ).
3. then do point 1 for text2 till text6. and print those also.


how would i go by this?
i know how to count the lines and all that

Code:
Private Sub Count_Click()
Dim Pieces1() As String
Dim string1 As String
Dim lines As Integer
Dim i As Integer


string1 = Text1.Text


Pieces1 = Split(string1, vbNewLine)

For i = LBound(Pieces1) To UBound(Pieces1)

lines = lines + 1
Count.Text = lines

Next i

End Sub
but then i wouldnt know how to read the content of that single line, and even how to read multiple lines.


Please help me with this!

thank you
Jeroen van Vierzen

Old Toolbar Keeps Returning
Hi all,

Has anybody had problems changing to a later version of a custom toolbar.

I have a toolbar that has a menu on it, once an option is clicked it runs a small VBA program. This toolbar was attached the workbook and when opened appeared on the receiving PC.

I added some more options a while ago and I had a lot of problems getting the new toolbar to appear. Again I've added more options and now I'm pulling my hair out because the toolbar is reverting back the original one, version 1.....

I've asked the user to delete the original file and toolbar. There is now nothing on the machine relating to my custom toolbar. I have then deleted the attached toobars from my workbook and saved. Next step is to reattach the latest toolbar to my workbook.

Again the user still gets the old toolbar from 2 versions ago.

Help!!!!!!

Cheers
Tom

VBA: Returning The Top 'x' Results.
I need to display 'x' number of results.

The 'x' is user defined.
The results are generated by a Query then displayed by a report.

I have tried the SQL TOP command, but it appears you cannot link that to an input box located on a Form direct to the Query.

I have tried to generate an incrementing number field in the query, but this was also to no avail. If this would have worked then I could simply limit the amount to display.

Any ideas on this are greatly appreciated.

Cheers,

Si.

Returning A Value, Not A Formula
Hey all, I need a little help with something pretty basic. I have a macro that performs a simple calculation. How do I return only the result, the integer information, to the cell without the formula tracking along with it?

ActiveCell.FormulaR1C1 = "=R[-1]C+1"

Thanks for any help on this!

XLS MsgBox Returning A Value
I'm an idiot. I'm sure this is a super easy fix and I'm just overlooking something.
Heres what I have


Code:
Private Sub Validate()
Dim EmpName As String
EmpName = Range("B2").Value
Ans = MsgBox("Are you" & " EmpName " & "?", vbYesNo, "Validating")
Select Case Ans
Case vbYes
' Code for yes
Case vbNo
Range("B3").ClearContents
Call GetName
End Select
End Sub
The Message box shows "Are you EmpName?" It doesn't show like, "Are you DrSwaity?" if thats what was in B2. I think it looks good, but obviously not.

One consideration is B2 contains a "=vlookup" formula. There is a value in the cell...

Anyways, thanks in advance!

Returning The Address
i whouldnt know what to google to find the answer to this so ill ask on a fourm. i whould like to make a program that can copy itself to another directory. i know how to copy just fine, my problem is that, i dont know how to return the current address of the program. say someone downloads my progam and saves it were ever(c:/downloads/stuff/) for example. how do i make my program return (c:/downloads/stuff/myprogram.exe) as a string, so i can make it copy it and save it to another directory?

Returning Focus To VB
I have a VB program which instructs an Application (AutoCAD), to do a number of things, including "zoomAll". THis sets the focus on the AutoCAD application. Then to proceed with the VB program's Code, I always have to manually click on the VB interface. This returns the focus to the VB program and so teh VB code is resumed.

The problem this is to be a server program so I need ensure that the focus is returned to the VB program automatically.....Any suggestions would really be appreciated.

Thanks

Gwyn

Returning Filenames
Hello.

Does anyone know how to return a list of filenames from a folder.

In a folder say H:Folder there would be some documents. Documentx, Documenty, Documentz. I would like to populate a list in excel with these filenames.

Hope this makes sense.



Martin

Returning The Value From A List Box
Alright, I have a list box and im using my variable.listindex which gets the value of the row that i have selected but i want to take the value that i have in the row. So just tell me.

Returning A Variable
Ok ive made an object, but there is still once piece of code i cant figure out. The object has a few variables (Dim Id As Integer), and has a function to give it the Id. But now If i want to call the ID while the program is running, how do I do it? I have another function called getID() but Im not sure what the command is so i can call that variable and use it. (similar to the return variable command in Java)

Dir Function Returning . And ..
I'm using the dir function to populate an array with the names of folders on a drive. It works fine if you specify the root folder

ex.
sFolders = Dir("f:", vbDirectory)

but if i specify a subdirectory, like this

sFolders = Dir("f:sub", vbDirectory)

it lists all the subdirectories off of f:sub but it also lists "." and ".." for the first two elements of my array.

Is there a way to stop this?
Also, is there a difference between dir() and dir$()

thanks

Returning Day Of Week
is there a simple function in vb that can return the first day of a given week.

for example week 3 in 2003 gives 13 januari

thnx for the help

Returning Enum
Module:

Code:
Enum type_Defcon
blue = -1
green = 0
yellow = 1
red = 2
End Enum

Public Defcon As type_Defcon
Form:

Code:
Private Sub Form_Click()
Defcon = Defcon + 1
If Defcon > 2 Then Defcon = -1
Debug.Print Defcon
End Sub
This will print the value of Defcon. But how can I print the names? like blue, green etc.

Returning ListIndex
How do i return the listindex from a item in a listbox if i only know the text?

i know how to return the text if you know the listindex

SelItem = List1.List (List1.ListIndex)

But the other way round isn't working...

Returning A Pointer From A DLL
Hi All,

This may be a stupid question (there are no stupid questions, just stupid people asking questions)....

This is my DLL function that returns a pointer to a buffer variable that is passed, as a pointer, the function:

char *PROG_GetHome(char *buff);

and I am trying to build the VB code that calls this function and I am having a little trouble.

Any ideas?

Thanks much, DM

Returning Printer Name
I have an application where I need to store a users selection of up to 6 different printers (various default label printers, etc). I am trying to use the Common Dialog to allow the user to select a printer to store, but cannot determine how to find the printer name once returned from the selection using the control.

Thanks in advance.

Returning An Array
how can i return an array from the function?


waqas

Returning An Error
In A function or Subrotine, is it possible to return an error to what called it? That way I can use the On Error command more easily.

Returning Values From A VB Exe
Hi All,
I am trying to write an exe file (required by a 3rd party vendor I am integrating my system with) that accepts an arguement (the ID of a particular record in a database) and select the values from the tuple associated with the ID from the database, concatenate the selected fields and return this concatenated string.

Is this at all possible. I mean if i create a standard exe, it is the form_load that runs and since it is a Sub it cannot return a value. I cannot use a dll because the vendor explicity states that an executable (exe) file must be used. It is their system that calls my exe file and I do not have control over how it calls my file. All it does it call my file with an input paramenter and expects the string returned when it calls the exe.

Any help is greatly appreciated. I am a novice to VB and I do apologise if my question sounds silly.

Thanks a million.

MI

Function Returning A Value
Could someone show me a quick demonstration of calling a function, and having that function return a value?

Returning A Value From A Form
Hi all,

I'm probably being dense here, but could someone enlighten me on how to return a value from a form in VB6?

Thanks,

-Utini

Returning DOS App Results
Is there a function to return the results of a DOS program into a variable? eg,
xxx ("C:windowssystem32ping.exe google.com", result) would return the output you'd get if you typed that into a dos prompt into variable result? Thanks

Returning Key Value From A Collection
Is there a way to return the key values from a collection?

Here's some code to illustrate what I mean:


Code:
Public Sub Save()
Dim fso As New FileSystemObject, ts As TextStream
Dim outputLine As String, i As Integer, setting As String
Set ts = fso.CreateTextFile(mFilename)
For Each setting In Settings
outputLine = setting.key & "=" & setting '<- if only this worked....
ts.WriteLine outputLine
Next setting

ts.Close

Set ts = Nothing
Set fso = Nothing

End Sub

Of course, the setting.key is invalid. What I want to do is find both the value of each member of a collection, and also the value of the key for each member. I supose I could just rewite the class to store the key and value in a small array, but I was hoping to make a shortcut in this way...

Any suggestions?

Returning The Value Between Two Characters
If i have

<one two three> how do i get the values between the < and the >?

thanks

Returning A Value And How Read It
Hi,

This question its a little simple, but I don't know how do it.


I just need to return a value of my EXE when the commandline have some letter ie. "/V", I need to return a Version of the EXE. and How I can read it from another EXE ???


Thanks
Mike

Help! Regarding Recusefolder Returning
I found this code. Is this code capable of returning just the filename and just the subdirfilename? Example:

1st_read.bin
Readme
New Folder1st_read.bin
New FolderReadme

I working around this, but couldn't figure this out. any help would be appreciated!!


Code:
Option Explicit

' Copyright © 2001 DonkBuilt Software
' Written by Allen S. Donker
' All rights reserved.

'************************************************************
' Takes a valid path to a folder and, using recursion,
' fills a listbox with the complete path and filename
' of each file in the folder passed in
'************************************************************


'************************************************************
' Folder/File attributes constants
'************************************************************
Const FILE_ATTRIBUTE_ARCHIVE = &H20
Const FILE_ATTRIBUTE_COMPRESSED = &H800
Const FILE_ATTRIBUTE_DIRECTORY = &H10
Const FILE_ATTRIBUTE_HIDDEN = &H2
Const FILE_ATTRIBUTE_NORMAL = &H80
Const FILE_ATTRIBUTE_READONLY = &H1
Const FILE_ATTRIBUTE_SYSTEM = &H4
Const FILE_ATTRIBUTE_TEMPORARY = &H100

Const INVALID_HANDLE_VALUE = -1
Const ERROR_NO_MORE_FILES = 18&
Const MAX_PATH = 255


'************************************************************
' Struct to hold file data
'************************************************************
Private Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type


'************************************************************
' Struct to hold data returned from API calls
'************************************************************
Private Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type


'************************************************************
' Struct to hold data returned from API calls
'************************************************************
Private gFileData As WIN32_FIND_DATA


'************************************************************
' Windows API declarations
'************************************************************
Private Declare Function FindFirstFile& Lib "kernel32" Alias "FindFirstFileA" _
(ByVal lpFileName As String, _
lpFindFileData As WIN32_FIND_DATA)
Private Declare Function FindNextFile& Lib "kernel32" Alias "FindNextFileA" _
(ByVal hFindFile As Long, _
lpFindFileData As WIN32_FIND_DATA)
Private Declare Function FindClose& Lib "kernel32" (ByVal hFindFile As Long)





Public Sub RecurseFiles(ByVal sFolderPath As String, objListbox As ListBox)

Dim hFindFile As Long
Dim ReturnValue As Long
Dim Filename As String

'Get First Directory Entry. File value returned will end in
'a null-terminated string.
hFindFile = FindFirstFile(sFolderPath, gFileData)

'Exit if there was an Error Getting First Entry
If hFindFile = INVALID_HANDLE_VALUE Then
FindClose (hFindFile)
Exit Sub
End If

'Initialize ReturnValue
ReturnValue = 1

Do While ReturnValue <> 0

'Remove the null charactor from Returned Filename
Filename = StripNulls(gFileData.cFileName)

' If it is a Directory but NOT the "." or ".." directories
' get all the Files in that directory (starts the recursion)
If Filename <> "." And Filename <> ".." And _
gFileData.dwFileAttributes And FILE_ATTRIBUTE_DIRECTORY Then

RecurseFiles Mid(sFolderPath, 1, Len(sFolderPath) - 3) & Filename & "*.*", objListbox


Else 'Keep getting files in current psStartingPath

If Filename <> "." And Filename <> ".." And Filename <> "" And Not _
gFileData.dwFileAttributes And FILE_ATTRIBUTE_DIRECTORY Then


'Now that we have the file, do something with it,
'in this case, add it to a listbox
objListbox.AddItem Mid(sFolderPath, 1, Len(sFolderPath) - 3) & Filename

DoEvents

End If

End If

' Get Next Entry
ReturnValue = FindNextFile(hFindFile, gFileData)

If ReturnValue = 0 Then

Filename = ""
Exit Do

End If

DoEvents

Loop

' Close Handle
FindClose (hFindFile)

End Sub


Private Function StripNulls(ByVal FileWithNulls As String) As String

Dim NullPos As Integer

NullPos = InStr(1, FileWithNulls, vbNullChar, 0)

If NullPos <> 0 Then

StripNulls = Left(FileWithNulls, NullPos - 1)

End If

End Function

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