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

File Handling In VBA For Access

Hi all,

Can anyone tell me how I can read a part of a filename?

I have the following structured filename: FAK2V021272003120553295.txt

Fak2 stands for the filetype
V02127 is a code
and 20031205 is the creation date followed by a number.

What I want to do is get the code witch is alway 6 digits after FAK2 and compare it with a list and if the match is found a macro has to be started.

can anyone help me out with this one?



View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Handling Text File - Random Access Files
Hi There,

I am writing a quiz program that uses a Random Access File (quoz.dat). Each question has 4 possible answers, which you selectg via CheckBoxs, then click go and an explanation popss up of the correct answer.

I have put the questions into a string "Q".

I have 2 questions,

How do I write a string to a combo bax caption, I have tried:

Combo1.caption = trim(Q.Answer1) - but i doesn't work?

2)Howdo I write the explaination to a messaage box?

MSGBOX (Q.Explanation) - Don't work either?

Any Help would be much appreciated.


Handling Records Without Access. Help!
I'm trying to write a program that fills list boxes from details held in record structures or tables, or whatever they're called in VB.
Filling a list box with a single item from a table is fine, but I want it to fill each line with the whole record in columns. I've just found out that a list box can't do columns like that. I need the program to be able to sort the displayed list, by the contents of different columns, rather than just the whole string displayed.

Any suggestions on what, if not a listbox to use?

Also, how to work it so that colums display fields properly?

Pleez help. Thanks.

Vb And Access Handling Error
I am trying to write vb code to handle error. My app allow the user to populate a Ms access database using vb and i want make sure all the fields are empty and that the user does not enter a productID (primary key) as a duplicate. I have the followiing:

Private Sub cmdSave_Click()
'Turn on the Error Handling
On Error GoTo Test
'Save the current Record
Call Enable_Buttons

'Errors are handle here:

If Err.Number < 0 Then
Err.Number = Err.Number - vbObjectError
End If

'Debuggind Purpose Only
'MsgBox "Error Number" & Err.Number

Select Case Err.Number

Case -245755
MsgBox "All your boxes are empty and/Or duplicate product ID"
Case 0
MsgBox "At least one one the boxes is empty"
Case Default
MsgBox "uknow error, this prgm will now close"
Unload Me
End Select
Resume Next

End Sub

I have no idea why it does not work and i do not know how to get each error number for each error this may cause (i need a special case for each error, for example, duplicate key, or only 1 field empty or all of them)

I always get the same error number

Thanks for your help

Handling Image In VB And Access
Dear Friends

I want to create a database which includes Images too. In access, OLE field can accept BITMAPS only, I want to put some JPEGS it is possible in Access. Also, I want to connect this OLE field in Visual Basic, No Control can hold, is this have any solution, that I can put images through VB

File Handling ( Addin Data Into Exist File In The Beginning Or The End )
Hello all.

How can I output only the first 128 bytes from a file?
How can I ouput only the last 128 bytes from a file?
How can I stor only 128 bytes into a file?

Those are 3 questions that I was thinkin about and searching for help without any luck.. for any information answer, THANK YOU! in advance! :

Yours, Yoni D.

Edited by - CRC-error on 10/17/2005 4:34:19 PM

Error Handling On Access Queries
I've got a problem with an access query that I'm running in my program.

Basically upon the loading of a form it executes an SQL statement. Problem is if the program is hooked up to a DB that doesn't contain the correct tables (e.g. "tblCountry") it causes the program to crash out.

How do I handle this kind of error correctly? I've read the error handling tutorial and that's given me a general idea about the whole area, but specific problems are hard to legislate for.

Access Handling Table Relationships From VB
I have two tables in my Access DB, Table1 and Table2. Table1 has a TABLE2_ID field that is linked by a relationship to ID field in Table 2. So for each record in Table1 there are several records in Table2. I'm sure any of you that have used Access before know what I'm talking about. I already have a connection to the DB(code below).
What I'm trying to do is enter a record into Table1 then later add the (sub)records the relate to it into Table2. If anyone has done this before I would appreciate any help I can get..
VB Code:
Dim db As ADODB.ConnectionDim rs As ADODB.Recordset Set db = New ADODB.ConnectionSet rs = New ADODB.Recordset db.Provider = "Microsoft.Jet.OLEDB.4.0"db.ConnectionString = "Data Source =" & App.Path & "SchTest.mdb"db.Open rs.LockType = adLockOptimisticrs.CursorType = adOpenDynamicrs.ActiveConnection = db 'rs.Open "Schedules"  'have some different sql statements that go here db.Close

Handling 2 Random Access Files With VB
I would appreciate if someone could help me how to handle (Open, Add, Search and transfer) 2 Random Access Files in VB.
Basically what I have is an example of order entry, where the header is the Order.txt file (which has three fields order number, customer number and date) and the Detail.txt file (which has order numb, quantity, descripyion and unit price). My main problem is, I have no clue how to associate both files, where when I'm adding or searching, how to deal it using them.
More details are, When I ask to the user to insert a order number via inputBox how do I get all data from both files???
Attached is the form to have an idea what I am looking for.


Handling Duplication In Access 2000
Here's my situation:
I have clients operating in different locations. Each client uses a copy of a master Access database when out of the office. When the clients return to the office they each upload data back to the master database. Clients can upload the same data so I would like to build a piece into my application that is able to determine if duplicates exist in the mater database. If duplicates exist, I want to give the team lead the ability to select which of the duplicates to keep.

To date my application can merge the various databases and determine if duplicates exist but I am having trouble determining how to give the option of selecting a duplicate to keep. I currently save the duplicate records to an array.

Any ideas would be great.



Handling Record Lock In Access
Could anybody shed some light on how to handle if a Access DB record is locked by another process, or perhaps how to detect the lock prior to manipulating it?

What I have is an App that is currently accessing the same table for two different processes. One is adding records and editing records while the other is just editing the existing records. I am currently using ADO and connection strings to create the recordsets on the table.

Any suggestion on the proper or industry standard approach for this?

Handling Date Error In Access
 Hi all ,
I want to write a error handler in VB for an Access Application

I have wriiten a routine that will chack if it is a date else replace it with todays date.

But my problem is wheneven i try to move to next field it gives me Access Error about daye not valid .

I am developing a form in Access and wrintg cod ein VB .

How can I turn this error mesages ,so that it will access my Error handling code

Thanking you

Access VBA / Macro Error Handling

I am printing a report in Access. A warning message appears informing me that some data may not be displayed - this is not a problem.

The problem is that when I click on Cancel, I get a runtime 2501 - The OpenReport action was cancelled. This error doesn't occur if I use a Macro instead of VBA. I have tried trapping the error but the code doesn't go as far as my error handler. I'd rather not SetWarnings to false either...

Any suggestions? Thanks.


Private Sub Print_Click()


Select Case PrintLabelsFor.Value
Case 1
'DoCmd.SetWarnings False ' rather not...
DoCmd.OpenReport "Customer Labels", acViewNormal ' error occurs here
'DoCmd.SetWarnings True
End Select

'got this far, exit
Exit Sub


Select Case Err.Number

Case 2501
'user cancelled print
Resume Next ' chance would be a fine thing!
End Select

End Sub

Opening An Access Database With Error Handling
I am trying to open an Access Database. If the Database Path is wrong, I want the code to give a Message Box saying unable to open the database. If the database DOES open, what is happening is the error occurs anyway. What is wrong with the error handling code? Thanks in advance!

Sub Main()
' Cannot open database.
On Error GoTo LoadErr
Dim lpDefault As String
Dim Temp As String * 50
File = App.Path & "Iniprefs.ini"
lpAppName = "General"
lpFileName = File
Path = "Path"
lpDefault = ""
GetOnLoad = GetPrivateProfileString(lpAppName, Path, lpDefault, Temp, Len(Temp), lpFileName)
Set Cn = New ADODB.Connection
Cn.Open "provider=microsoft.jet.oledb.4.0;persist security info=false;data source =" & Temp
Set rsRecordSet = New ADODB.Recordset
rsRecordSet.Open "SELECT * FROM CUINFO ORDER BY CUName", Cn, adOpenStatic, adLockBatchOptimistic
rsRecordSet.Open "SELECT * FROM CUINFO ORDER BY EmployeeName", Cn, adOpenStatic, adLockBatchOptimistic
rsRecordSet.Open "SELECT * FROM KB ORDER BY ID", Cn, adOpenStatic, adLockBatchOptimistic
MsgBox "Error opening database."
Resume Next
End Sub

Handling Access Database Null Values

I am having difficulty retrieving values from new columns in my vb app because I am always returning a null value. How is it that you code for a null value and change it to a "" (empty string on the fly). What I find that I end up doing is, going back and putting a default value (like "0") into each field which is a pain because I may have to do this several hundred times. There must be a better way.

For example: I have two columns (yes, I know but go with me on this) Column 1 is FirstName, Column 2 is LastName. I have ten names in my dB and now I want to add a middle name column to this. So I add the column and then using the vb app, try to retrieve one of the names in a list box and try to put the 3 parts into three textfields, and I get an error trying to handle the null value.

Thanks for the help.


Access 2000 Multi-User Handling
I have developed this application for a multi-user environment and was wondering what is the limit of transactions or connections an Access 2000 database can handle without falling over ?

Also what are the Pro's and Con's of a mulit-user environment ?

A VB turned PHP geek

Handling Nulls In Date Fields Using ADO/Access
I added a couple of fields to my table, fldDateAdded and fldDateModified. When a record is saved these fields are written automatically, so normally they won't contain any null values...BUT...
...since I added these fields to an existing db there are records where these values are null. To protect against null values in a text field I just concatenate a "" to the recordset. How do I do that with a date field?

What I have done so far is change the datatype of the variable I use from Date to Variant. Then when I retrieve a record I concatenate an "" to the end.
Code:mvDateAdded = rs("fldDateAdded") & ""
That seems to be working, but if possible I would rather not use the variant datatype. How would I handle nulls with Date datatype?

God Bless America

Handling The Close Button On An MS Access Form
I would like to know when I use has just clicked on the close button of an Access form. Is there any API's I can call. I've never used API's before, but if there is one how can I handle the event?

Access 2000 - Pass Through Query Error Handling
I have a subform, which has it's SourceObject set to a Pass Through Query. When an error occurs, Err.Description simply gives a generic message for any ODBC error that occurs - "ODBC--call failed." What I am expecting to be reported is the native Oracle error, e.g. "ORA-00942: table or view does not exist".

If I execute the query solo - double clicking on the query icon, then I get an error message that displays both error messages - "ODBC--call failed." and "ORA-00942: table or view does not exist".

Can someone explain why I do not see the native error message during code execution for the subform? Or perhaps a work-around solution?

The only work-around that I have found so far is to execute an ODBC query first, then perform the same query using the pass-through. The ODBC call returns the native error message, so if there is an error, I receive it, and the pass-through is never instantiated. The problem with this (besides the fact that it is a hack) is that the query has to be executed twice. Here is the code, minus the boring details...

Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset

'Set SQL in Pass-Through Query
CurrentDb.QueryDefs(strQryName).SQL = Trim(strSQL)

'Execute the SQL using an ODBC call, native description is returned
rs.Open strSQL, CONN, adOpenKeyset, adLockOptimistic, adCmdText

'Set the SourceObject of the subform in order to implicitly execute the Pass-Through Query and display the recordset
subPassThru.SourceObject = "Query." & strQryName

I have also tried to use just the ODBC call (without the Pass Through), however I have not been able to figure out how to display the subform in datasheet view. When I try to set the recordsource of the subform, it appears to be nested within the main form's recordset. Anyhow, suggestions are welcome.



MS Access Currency And Double Data Type Handling
I want to know how VB handles the Currency (General Number) and Double data types. What exactly is the difference? I want to set the currency to handle uptp 2 decimal digits but I don't want it to automatically get rounded.

Also in VB code, what data type should be used to handle Currency?

Some of my code sections are automatically rounding some currency figures.

File Handling
Being a beginner in VB I am easily confused about a lot of things. Today it's File Handling. I would like to ask the experts and gurus about how they would go about saving data so it can be recalled at a later date.

Here's what I've got:

I used to be a TV Sports Announcer for Hockey. To prepare I made player cards for every player in the game. I had to write these for every game, 80 games, 2 teams 30 players and coaches per do the math, a lot of writers cramp.

I have written a few smaller programs, however, now I think I have bitten off more than I can chew. How would you handle saving the data for this program. Please keep in mind that I have read about databases, and I was so confused, I gave up on that...for now. I just need to able to call up any 1 player and have him properly displayed on a card.

Here's a very basic example of my program
Assume all my variables listed are as Strings

I'll create 2 players
(TB is TextBox on form)


99 Wayne Gretzky 3 8 11 Points in 5 Straight Games

PlayNum = "99"
PlayerName = "Wayne Gretzky"
GoalsX = "3"
AssistsX = "8"
PointsX = "11"
HeroX = "Points in 5 Straight Games"

4 Bobby Orr 5 13 18 Most Pts For Defenseman get the picture.

Assuming that these players are on the same would I want to create my file structure for handling the data?

One Folder For every Team?

In each Team folder should there be 1 file for every player (20-30 files)

Or Should I create 1 file and have 20-30 records on it? (If this is the case, I have no idea how I would extract one particular player.)

I humbly ask for your help here. If nothing else I am enjoying the learning process.

File Handling In Vb
I have a university assignment due in over the next week. I have to produce a cash point program (atm). I have to construct a program that allows the creation of customer information such as account number, customer name, openning balance and credit limit. This program has got to work as if it is a real cash machine. I have no idea how to store the customers information in file handling. Can anyone help me please?


File Handling
When I attempt to make a string variable to store a path to a file I wish to open and then open it, then the program doesn't open the file and it quits the function.

In point, the following code is an example:

loadFile = App.Path & "Magics" & tempMagicFile

Open loadFile For Input As #1

VB6 File Handling

I have an interesting problem that I'm hoping someone can assist in pointing me in the right direction.

I have a source .txt file containing a list of files (the files are located in several directories, sub directories, drives, etc) that I need to delete. This deletion needs to be automated within the application I am attempting to write.

So far I have created a file browser to locate the source file, a list box to display the content of the source file so that the user can verify that it's the correct file & now I need to process the contents of the list box (or original file) and delete all the files that are detailed.

Unfortunately the files that are to be deleted are not in a common folder & their names differ on each run as do their extensions. In addition the source file name is also different for each instance.

I've tried to pass the contents of both the list box & the file to a variable & then do a "Kill variable" command, but VB returns an error that it's not a valid file name.

Everything I've tried returns the same result.

Any ideas gratefully recieved.

File Handling
One quick quesion : how you can find if a path (folder) is already created ?


if thefunctionthatidontno(app.path & "TheFolderThatIWantToSeeIfHeEsxit") then DirectoryIsCreated =true

File Handling Help!!!
A series of files are being loaded into a Database in my program, but I want to wait until the anti-virus program scans them (anti-virus runs automatically)

Is there a way I can tell that the anti-virus program is done with the files....something like checking the File Handles to see if they are already open?

File Handling
how do i check if a file is present (i know the name) and if present delete it...

create it

Help Help Help ..file Handling..!!

i used the following code to open a file in binary mode and get the data to a buffer. but i got an error "52 Bad file Name or Number", i opened many files using this code but now i tried a file having size of 21MB and got this error..

how can i solve this ?? i am supposed to handle large files..!!

the code is as follows...
and i have to send the buffer to another application running in a remote machine..

please help

Dim Buffer() As Byte
' get a free filenumber
intFnum = FreeFile
' set the buffer size
ReDim Buffer(FileLen(strFilePath & strFileName) - 1)
' open the doc file to be send
Open strFilePath & strFileName For Binary Access Read
Lock Read As intFnum
' read the contents of doc to buffer
Get #intFnum, 1, Buffer
' close the file
Close #intFnum

File Handling
Does anyone know where i could look to find a function that will encrypt a file, and decrypt it. Just looking for a premade function that could encrypt a jpeg (and other file types in future projects).

I have looked around and not found any info... and despite wanting to learn about encryption, XOR, and other suggestions I got... I just want to finish this project for now.

Is this really that uncommon of idea?

Thanks in advance.

File Handling
Sorry, started a new thread cause once people see replies they generally don't read posts, and this is all that is holding up my project.

What is the best way to encrypt or scramble an image so that it is only viewable when I open a program and enter a password?

The program needs to support the addition of daily photos, as it will be a journal of sorts.

I thought about just using input/output to read the file to a new file name and change the file type. But then I would still need to know how to sncrypt or scramble the index of the files.

Thanks in advance.

File Handling
I was wondering if someone could help me.
I've started coding in VB pretty recently, and my current project is that I'm trying to write a utility which will read the path of a database from the registry, and then backup the folder that the database is in to another directory.

This is probably pretty basic sounding to most of you guys, but how do I get VB to copy entire directories rather than individual files ?

Here is a very rough draft of what I'm currently using to copy individual files :

Dim filesys As Object
Dim SrcPath As String 'This will hold the Source file path
Dim DestPath As String 'This will hold the destination file path

Private Sub Backup_Click()

Set filesys = CreateObject("scripting.FileSystemObject")

SrcPath = "C:filesfile1.mdb"
DestPath = "C:ackupfile1.mdb"
filesys.copyfile SrcPath, DestPath 'Copy file to relevant place

If err Then
MsgBox "****, File could not be copied because : " & err.Description
End If

MsgBox "Great, Files successfully copied from " & SrcPath & " to " & DestPath

End Sub

Thats quite rough but I'll be refining it later. The main problem at the minute is that I need it to have the ability to copy entire dirs rather than individual files, can anyone please shed some light on this, as I'm not sure how to do it.

Thanks for your time :-)

File Handling
I am trying to do a visual basic project in my school. We have a file which is in the text format called 'schedule' created everyday. This schedule file should be stored in the network with the date included in it so that it would be unique. In the program we should be able to view and search for the schedule for any particular day. Any input would really be appreciated.

File Handling...
OK peeps....need a point in the right direction

I am making my own "installer program"...however I have never done file handling....and no i dont want to use wizards etc....i need to make this installer myself

I need VB code examples of how to

1 - create folders
2 - copy files from one folder to another
3 - run an exe

thanks in advance....hope someone can point me in the right direction

Handling A File
How can i find whether a file exsists or not?

Dim iFile As Integer, sText As String

iFile = FreeFile

Open App.Path & " ext.txt" For Input As iFile
Input #iFile, sText


XML File Handling Using VB
i am a vb 6.0 programmer

presently i can create following xml using vb


using MSXML2.IXMLDOMElement , createelement properties
now i want to add child to main root
that is


how can i acheive this ....

File Handling
i want to know that a file(image .jpg) is in use or free that is if my program going to copy a file but at the same time another program is using that same file,in this case i will get error.

To avoid this probleam i want know that specfic file is in use or not before copying by my program.

Pls help me to come out.

Thanks in Advance.

File Handling With VB 6.0
how can we do following in VB6.

1. Getting data from text file (*.txt) comma separated values.

2. Generate a key on the basis of each line in the text file. For example text file contains first line as follows:

001, David Copper, Andrew Symonds, House No. 256 Manchester

Key on this file will be as follow:


A from Andrew, S from Symonds and Manchester from Address field.

3. After generating key merge every record's key with the record, can be at the end of line.

4. Now the vb interface give functionality to create new database then its table. All data should be shifted to the table which consists of all the fields with comma separation.

5. Sorting should be done on the basis of "key" with every record in the table using SQL.

6. Now a button should have functionality to show records that are duplicates in "Data Grid Control ".

how can we do this in VB 6.

Need Help With File Handling
I am designing a program which reads questions from a text file and then stores it in a label. The questions are in option boxes, if the user picks the right option box, they proceed to the next screen. I was told I can do it using an array, how can I do this?

FIle Handling
Hi all

I have a small problem

I have two text boxes (Multiline = TRUE) and a folderpath

textbox 1) contains some data to be added in all the files

in the folderpath (files can be in folderpath or in Sub folders of it)

If that text is already present msfbox ("Error text present")

user can also enter the test to be deleted in this textbox 1

text box 2 can have some text which will b replacing the test

in the box 1.

I e particularly I want to do add mod del on the text box 1

mod text is given in box 2. addition only if not present

How can i read everyline in the text box ? n do these operations?

can ne body help me with the code?


File Handling
Does anyone know of a program that will show me open file handles on a directory?
What I am trying to do is see when my program is leaving a file handle open.

The issue I am having is that I use a directory for local stuff then I copy the data back to the database. Kind of like a "check out"/"Check In" process. So when I "Check Out" a file, in my program directory i create a folder with the filename on it, and i put other binary files in that directory. Then when I "Check In", i open the files, copy data back to the database. Delete all the files in the directory, and delete the directory. Now my issue is that I am getting error 75 "Path/File access error" when i do:

RmDir sFilePath

I found out about using the Dir$ function to check to see if a file/folder exist, and how it doesn't close it's file handle so you have to point it at another directory to release it. However I am still having the problem.
Also I tried the "Reset" command. Its supposed to close all open files.
I've also tried loading the scripting.FSO object, but it yields the same result. Also, I check to make sure there are no files in that directory then I delete the directory. This is my current function:


Dir$ app.Path, vbDirectory

'Kill strCurrDir & "*.*"

'Ryan's Auto Delete
sFileName = Dir$(strCurrDir & "*", vbNormal or vbHidden)
While sFileName <> ""
Debug.Print sFileName
Kill strCurrDir & sFileName
sFileName = Dir$

RmDir strCurrDir

So, I believe i have 2 options:
1) Find the open file and close it properly
2) Find a way to kill all file handles in a certain directory so I can remove the directory

Anyone have any ideas?


File Handling
Hi all

in VB if we read a file n write the containts to the other file

then in case u r joining some strings then we use '&' operator

But while writting to the file this operator writes a default

space in to the two strings

e.g. print #2, "this is" & "Temp string"

then Output will b -> this is temp string

But I want to remove this Space n want Output as

This isTemp string

How should i do it?


File Handling
Hi there

I want to open a text file then read a particular word in it till the end and want to print that particular line containing that word in another text file how do I do it?

can NE body give me the code for it?


File Handling In VB6.0
In my application, I want to read the contents of a .pdf file and put it in a seperate file and in the same file itself I want to add the contents of a .doc file. After adding it, I want to read the contents of the pdf file alone or .doc file alone whichever is selected from that newly created file. How can I do it in VB6.0

Thanx in Advance...

File Handling
i'm building a logfile that records details of transactions taken place , once the file reaches a certain size i want the first record to be deleted and for the second record to become the first , third to become the second. Any ideas ???????

File Handling

Does anyone know how to move a file in VB



File Handling
I have a Vb program, running on a NT server, which processes a file that's ftp'd from an AS400.
problem is that occasionally processing begins before the file is fully copied down.
Is there any way of checking that the file ic completetely copied down before processing begins.

File Handling
I want to open a text file in Read-write mode is it possible in VB???


File Handling
Ratz!! I've 4got10 howto do this : -

What I want is to add some text to the end of and existing file (with some data already in it). Later I want to find that text and remove it from the file. I mean delete it from the file

I need to know this ASAP

Need Help With File Handling
Hello, I'm making a program with an option of saving large file to several disketts, I have several "holes" in my program, which i can't solve:

1) How can I know if a diskette is in the drive??? (Floppy)
2) How can I split lets say, 2MB File into 2 diskettes???
3) And if it's not too hard, can I compress the file???

10Q very much for youre help!

File Handling

So I have my log file, I have open it like this:

Open ("mylog.log") For Output Shared As #DebugFile

And as far as I am aware the Shared key word will allow other applications to access it??

But say I write somthing into the file, if I open the file with notepad before I close the file nothing appears.

What I am doing wrong?



Copyright 2005-08, All rights reserved