473,387 Members | 1,641 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Renaming a field based on content

Hi Folks,

I have been given a CD with approx 130 .xls files (bean-counters!) that I
would like to import and merge to ONE table (tblTradeshow).

The XL files are *similarly*, but not identically structured, and the first
row does NOT contain field names.

Some (actually most) of the column names *are* the same in all of the
spreadsheets.

Some sheets have additional columns for extra data (core deposit value, case
qtys, container size, etc), none of which I *really* need, but would like to
preserve if possible.

All sheets contain several blank columns and rows. Some of the blank columns
are between colums of data that I need.

I'm attempting to rename the fields in newly created tables according to
what I can find in each "Column Heading" (which is not on the first row)
Renaming the fields (common denominator approach) is the first step in
appending them to a single table.

The problem that I am running into, I have discovered, is that you cannot
change the field names while you have the recordset open, so I have
"kludged" a solution by creating duplicate tables at run time and modifying
them... so now I have 260 seperate tables!

I have succesfully automated the import and merge procedure , using the code
below.
After this is completed, I am using a function to delete all of those 260
"temp" tables.

All of this code *does* seem to do the job ... but all of these variables,
recordsets, looping, and deletion seems to be redundant.
Can anyone suggest a better way to do this?

Or should I just leave it alone, and be happy that it works? :)

TIA, Don

================================================== ============
Private Sub cmdImportMergeXL_Click()

Dim MyDB As DAO.Database
Set MyDB = CurrentDb
Dim rst As DAO.Recordset

Dim rstFiles As DAO.Recordset
Set rstFiles = MyDB.OpenRecordset("tblFileNames")

Dim MyDir As String
Dim MyFile As String
Dim MyPath As String
Dim FileSpec As String

Dim Pos As Integer
Dim strTableName As String
Dim blnAccepted As Boolean
Dim MySQL As String

Dim Msg As String
Dim CR As String
CR = vbCrLf

Dim OldField As String
Dim NewField As String
Dim ExistField As Field
Dim ExistList As String
Dim rstExist As DAO.Recordset

'Start by browsing for the drive/directory containing the XL files
'-----------------------------------------------------------------
MyDir = BrowseFolder("Find the directory containing the desired files")

FileSpec = MyDir & "\*.xls"
MyPath = MyDir & "\" & Dir(FileSpec)
MyFile = Dir(FileSpec)
'This section loops thru the files in the directory one at a time
'and performs the import operations
'-----------------------------------------------------------------
Do While Len(MyFile) > 0
Pos = InStr(1, MyFile, "store") 'eg F:\Bodyshop Products\Bodypro
coveralls store.xls
strTableName = "tbl" & StripString(StrConv(Mid(MyFile, 1, Pos - 1),
vbProperCase))
'Result: "tblBodyproCoveralls
DoCmd.TransferSpreadsheet , acSpreadsheetTypeExcel97, strTableName,
MyPath, False

'We cannot modify the table that we are importing because we
'have an open recordset, so I make a duplicate copy that I can
'mess around with.
DoCmd.CopyObject , strTableName & "1", acTable, strTableName

Set rstExist = MyDB.OpenRecordset("tblTradeshow", dbOpenTable)
'Build a list of existing "tblTradeshow" fields.
'This code needs to be placed here so that this list
'gets refreshed between each table import operation.
'----------------------------------------------------------
With rstExist
For Each ExistField In rstExist.Fields
If Len(ExistList) > 0 Then
ExistList = ExistList & ", " & ExistField.Name
Else
ExistList = ExistField.Name
End If
Next ExistField
.Close
End With

'This section deals with the problem of naming the imported
'table fields. Unfortunately, the first row of the spreadsheet
'did not contain field names, so we have to hunt them down...
'----------------------------------------------------------
Set rst = MyDB.OpenRecordset(strTableName, dbOpenDynaset)
Dim fld As Field
Dim fldName As String
Dim fldList As String
fldList = ""

With rst
.MoveLast 'Populate the Recordset
.MoveFirst
'Find the row that contains the field names, by searching for
'a product "Line" ... a 3-letter code that identifies the mfr.
.FindFirst "F1 = 'Line'"
For Each fld In .Fields

OldField = fld.Name
NewField = StripString(fld.Value) 'Remove spaces and
punctuation from field name

Select Case NewField
Case "Part"
NewField = "PartNumber"
Case "" '(blank)
GoTo SkipField
Case Else

'If we find a new field name that is not already
'in tblTradeshow, we decide if we want to add it.
If InStr(1, ExistList, NewField) < 1 Then
Msg = ""
Msg = Msg & strTableName
Msg = Msg & " contains: "
Msg = Msg & NewField & CR
Msg = Msg & "where I'm expecting a field name" & CR
& CR
Msg = Msg & "Do you want to use this as the field
name? "

If MsgBox(Msg, vbYesNo) = vbYes Then
'This is where the field name actually
'gets added to tblTradeshow
MySQL = ""
MySQL = MySQL & "ALTER TABLE tblTradeshow "
MySQL = MySQL & "ADD COLUMN "
MySQL = MySQL & NewField
MySQL = MySQL & " TEXT"
MyDB.Execute (MySQL), dbFailOnError
Else
'User decides NOT to add this field.
GoTo SkipField
End If
End If
End Select

'Build a list of field names
'for the table being imported.

If Len(fldList) > 0 Then
fldList = fldList & ", " & NewField
Else
fldList = NewField
End If

'Now call a function that renames the fields
'(in the duplicate table)to the field names
'that we have found above.
Call fSetFieldName(strTableName & "1", OldField, NewField)
SkipField:
Next fld

.Close
End With
Set rst = Nothing
'Now that we have checked / changed /added fieldnames we can transfer
'(merge) the data into a common table ("tblTradeshow")

If Len(fldList) > 0 And InStr(1, fldList, "RegCJ") > 0 Then
'Eliminate empty ROWS
MySQL = ""
MySQL = MySQL & "INSERT INTO tblTradeshow ( "
MySQL = MySQL & fldList
MySQL = MySQL & " ) "
MySQL = MySQL & "SELECT "
MySQL = MySQL & fldList
MySQL = MySQL & " FROM ["
MySQL = MySQL & strTableName
MySQL = MySQL & "1] "
MySQL = MySQL & "WHERE (((IsNumeric([RegCJ]))=True));"
'Debug.Print MySQL
MyDB.Execute MySQL, dbFailOnError
blnAccepted = True

Else
'Debug.Print MySQL
Msg = ""
Msg = Msg & strTableName
Msg = Msg & " has no valid fieldnames, and will be skipped."
MsgBox (Msg)
blnAccepted = False
End If
'Add the imported filenames to the table
With rstFiles
.AddNew
!FilePath = "#file://" & MyPath & "#"
'This converts the filepath string to a hyperlink,
'which allows the user to open the XL file from a subform link
'for diagnostic / compatison reasons ... "Show Me!"
!Imported = blnAccepted
.Update
End With

Me.Refresh
'There are 2 subforms on this form ... both based on "tblFileNames"
' "sbfFilesImported" shows successful imports
' "sbfFilesRejected" shows failed attempts. (Import fails if no Line
Code is found.)
MyFile = Dir 'Import the next XL file in the directory.

If Len(MyFile) > 0 Then
MyPath = MyDir & "\" & MyFile
End If
Loop

Set rstFiles = Nothing
Set rstExist = Nothing
Set rst = Nothing
Set MyDB = Nothing

Msg = ""
Msg = Msg & "XL Data import completed." & CR & CR
Msg = Msg & "Would you like to delete the TEMPORARY tables?"

If MsgBox(Msg, vbYesNo, "Confirm Deletion") = vbYes Then
fDeleteTempTables
End If

End Sub

--
TIA,
Don
=============================
Use My*****@Telus.Net for e-mail
Disclaimer:
Professional PartsPerson
Amateur Database Programmer {:o)

I'm an Access97 user, so all posted code
samples are also Access97- based
unless otherwise noted.
=============================
Nov 12 '05 #1
1 3382
Cloning recordsets would help you eliminate duplicate tabledefs.

Example
Dim db as Database
Dim rec as DAO.RecordSet
Dim strNewFieldName as String

Set db = CurrentDB()
Set rec = db.Openrecordset(<<<YOUR TABLE HERE>>>)

With rec
.Clone
<<<FIND INFORMATION TO BASE FIELD CHANGE ON>>>
Call FieldChanger(strNewFieldName)
Nov 12 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: jyoti | last post by:
Hi there, Our organization's web site requires a lot of content updates. I like to develop a browser based content management system in asp. I like to show my end users exactly live format of our...
6
by: Steve Speirs | last post by:
Hi I'm trying to show/hide a simple piece of text and a text field on a form based on what choice is made from a drop down box. <select name="dropdown" size="1"> <option selected...
1
by: Don Leverton | last post by:
Hi Folks, I have been given a CD with approx 130 .xls files (bean-counters!) that I would like to import and merge to ONE table (tblTradeshow). The XL files are *similarly*, but not...
14
by: SpyderSL | last post by:
Hey, I have created an access form, in which I have a drop down with employee names. These are the steps I would like to happen: 1. A user will enter a number in FIELD A 2. The user will...
1
by: compl | last post by:
I have a database that I need to restrict the ability to edit one field based on another. The two fields are DOS (date) and Amount (currency). I only want the users to be able to edit the Amount...
4
by: whamo | last post by:
I have the need to populate a field based on the selection in a combo box. Starting out simple. (2) tables tbl_OSE_Info and tbl_Input; tbl_OSE_Info has three fields: Key, OSE_Name and OSE_Wt...
10
by: dkyadav80 | last post by:
<html> /// here what shoud be java script for: ->when script run then not display all input text field only display selection field. ->when user select other value for institute only this...
5
by: Shortstuff12345 | last post by:
I'm trying to use VBA code to disable a field based on the value of another field in a form. The code I have properly updates the enabled property of the field when it changes; however, it changes...
3
by: dileshw | last post by:
I have a form where I want a third field to be autofilled by a certain text based on the content of 2 previously entered fields of data. I put this following code into an on_click event of a button....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.