473,546 Members | 2,468 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Change field names to first row of table

Bob
Hi all,

I've got a table that I've imported and it has junk at the top of the
table, so after import I run a delete query to remove the junk lines
then I'm left with the field names I want for the table at the top of
the table but the field names currently are 'field1' etc, so how do I
rename the field names to the fields on the top row of the table.

Cheers,

Bob

Mar 23 '07 #1
4 22477
Bob

Bob wrote:
Hi all,

I've got a table that I've imported and it has junk at the top of the
table, so after import I run a delete query to remove the junk lines
then I'm left with the field names I want for the table at the top of
the table but the field names currently are 'field1' etc, so how do I
rename the field names to the fields on the top row of the table.

Cheers,

Bob
Actually, to add to that I would like to change the fieldname to the
first Row of the table + the second. So for example...

Field1 Field2 Field3
Customer Customer Customer
ID Name Street Address
12321 David Park 452 Walker Ln
12455 etc

so for this example I want Field1 to equal 'Customer ID' and field2 to
equal 'Customer Name' then delete the first two rows so there's only
the actual data left....

Mar 23 '07 #2
"Bob" <sc*******@colo nialfirststate. com.auwrote
I've got a table that I've imported and it has
junk at the top of the table, so after import
I run a delete query to remove the junk lines
then I'm left with the field names I want for
the table at the top of the table but the field
names currently are 'field1' etc, so how do I
rename the field names to the fields on the
top row of the table.
If the column names were all in the first row, you could specify that in the
Import Wizard, and not have to do any post-processing. It is a little
unusual for the Column Headings to be split over two rows, but you could
write VBA code to do what you want, after you have imported the information
into a table; or, perhaps, depending on the format of the data that is being
imported, before or as you import it.

Larry Linson
Microsoft Access MVP
Mar 23 '07 #3
On Mar 22, 11:34 pm, "Larry Linson" <boun...@localh ost.notwrote:
"Bob" <scrawf...@colo nialfirststate. com.auwrote
I've got a table that I've imported and it has
junk at the top of the table, so after import
I run a delete query to remove the junk lines
then I'm left with the field names I want for
the table at the top of the table but the field
names currently are 'field1' etc, so how do I
rename the field names to the fields on the
top row of the table.

If the column names were all in the first row, you could specify that in the
Import Wizard, and not have to do any post-processing. It is a little
unusual for the Column Headings to be split over two rows, but you could
write VBA code to do what you want, after you have imported the information
into a table; or, perhaps, depending on the format of the data that is being
imported, before or as you import it.

Larry Linson
Microsoft Access MVP
I see two potential wrinkles here:

1. Since tables are unordered, you'll need to let Access add its own
Autonumberprima ry key (named [ID]) during the import so you can
determine with certainty what the "first two" rows of the table are.

2. There would be problems with trying to change the column names
while the table is open. My approach would be iterate through the
columns to determine their new names, save them in a Dictionary
object, then close the recordset and alter the column names via a
TableDef object.

So, for my test table...

ID Field1 Field2 Field3
1 Customer Customer Customer
2 ID Name Street Address
3 12321 David Park 452 Walker Ln
4 12455 Mike McMack 750 Virago St

....I would do something like this:

Sub TableFix()
' requires references to:
' - Microsoft DAO
' - Microsoft Scripting Runtime
Dim cdb As DAO.Database, rst As DAO.Recordset, _
tbd As DAO.TableDef, fld As DAO.Field
Dim NewFieldNames As New Dictionary, strNewName As String
Dim OldName As Variant

Const TblName = "Foo"

Set cdb = CurrentDb
Set rst = cdb.OpenRecords et( _
"SELECT * FROM [" & TblName & "] " & _
"WHERE [ID]<=2 " & _
"ORDER BY [ID]", _
dbOpenSnapshot)

For Each fld In rst.Fields
OldName = fld.Name
If OldName <"ID" Then
strNewName = ""
Do While Not rst.EOF
strNewName = strNewName & rst(OldName).Va lue & " "
rst.MoveNext
Loop
NewFieldNames.A dd OldName, Trim(strNewName )
rst.MoveFirst
End If
Next
rst.Close
Set rst = Nothing
Set fld = Nothing

Set tbd = cdb.TableDefs(T blName)
For Each OldName In NewFieldNames
tbd.Fields(OldN ame).Name = NewFieldNames(O ldName)
Next
Set tbd = Nothing
Set NewFieldNames = Nothing

cdb.Execute _
"DELETE * FROM [" & TblName & "] " & _
"WHERE [ID]<=2", _
dbFailOnError
Set cdb = Nothing
End Sub

Mar 23 '07 #4
Hi Bob,

Here's an *idea*...

1.) Create a properly structured "Template" table with an AutoNumber field,
correct field names / data types ...etc.
2.) Make a copy of the "template" table, renaming it to the "good" table
that you want to use for your forms and reports, etc.
3.) Design an append query that filters out the junk, and appends the good
data.
4.) When it comes time to refresh the data from a new import file ... delete
your "good" table, make a new copy of the "template" (as in step 2 above)

Here's a code sample (long) that will hopefully explain how I have automated
the entire import process.
What used to take an hour to do now takes just seconds, so this strategy
will be worth the time investment (IMHO)

This code also calls a couple of custom functions and subs that I have
designed, but not included. Many of the variable are declared in the form
declaration section as they are used by multiple procedures.

If you're REALLY interested, let me know ... and I'll post (or e-mail) them
as well.
Private Sub cmdImport086_Cl ick()
On Error GoTo cmdImport086_Er r

'============== ========== Step 1 =============== ===========
'============== ====== Test Data Path =============== =======
MyPath = Me.txtDataPath
Me![txtProgress].Visible = True
Me![txtProgress].SetFocus
Me![txtProgress].Text = "Testing Data Path"
Me.Refresh
DoCmd.Beep
Me![txtProgress].SelStart = 0
Wait 2, False
TestDataPath 'Call Sub

'============== ========== Step 2 =============== ===========
'============== = User FileName Confirmation ===============

CR = vbCrLf

Msg = ""
Msg = Msg & "You are about to import data from: " & CR
Msg = Msg & MyPath & CR
Msg = Msg & "Press 'Yes' if this is correct or 'No' to set Data Path"

If MsgBox(Msg, vbYesNo, "Check Data Path!") = vbNo Then
Me.Dirty = False
Me![txtProgress].SelStart = 0
Wait 2, False

FindPF
End If

'============== ========== Step 3 =============== ===========
'============== ======= Safety Check =============== ========
' Filename MUST be "RPT086" or program exits

Me![txtProgress].Text = "Checking File Name"
Me.Refresh
DoCmd.Beep
Me![txtProgress].SelStart = 0
Wait 2, False

If InStr(1, MyPath, "RPT086", vbTextCompare) Then GoTo Step4

Msg = ""
Msg = Msg & "You are attempting to import the wrong file!" & CR
Msg = Msg & "Please click on the 'Set / Verify Data Path'" & CR
Msg = Msg & "button to attempt to find it," & CR
Msg = Msg & "OR follow steps 1 & 2 to recreate it. "
MsgBox (Msg)
Me![cmdSetDataPath].SetFocus

Exit Sub

Step4:
'============== ========== Step 4 =============== ===========
'============== ====== Import RPT086.PF =============== =====

Me![txtProgress].Text = "Deleting / recreating import table "
Me.Refresh
DoCmd.Beep
Me![txtProgress].SelStart = 0
Wait 2, False
'Delete the old table...
If IsTableQuery("" , "RPT086") Then
DoCmd.SetWarnin gs False
DoCmd.DeleteObj ect acTable, "RPT086"
DoCmd.SetWarnin gs True
End If

'Copy the blank(template) table, renaming it to "RPT086"
DoCmd.CopyObjec t , "RPT086", acTable, "RPT086Template "
'Now that we have correctly structured table (with ID, Line1, Line2)
'we can import the data.

Me![txtProgress].Text = "Importing TAMS report"
Me.Refresh
DoCmd.Beep
Me![txtProgress].SelStart = 0
Wait 2, False

DoCmd.TransferT ext acImportFixed, "RPT086 Import Specification", "RPT086",
MyPath, False, ""

'Delete the ImportErrors table if it exists. (It shouldn't.. and I don't
need it.)

If IsTableQuery("" , "RPT086_ImportE rrors") Then
DoCmd.SetWarnin gs False
DoCmd.DeleteObj ect acTable, "RPT086_ImportE rrors"
DoCmd.SetWarnin gs True
End If

'============== ========== Step 5/6 =============== ===========
'============== ====== Find / Fill Line Codes =============== =
' Purpose: To first find and record the first instance of each
' "Product Line", then fill that value down for a range of records.

' Open, populate,and get the recordcount from the recordset.
Me![txtProgress].Text = "Finding product line codes."
Me.Refresh
DoCmd.Beep
Me![txtProgress].SelStart = 0
Wait 2, False

MySQL = "" 'Initialize String to nothing.
MySQL = MySQL & "SELECT StripSpaces([PartNumber1] & [PerCar1] & [Retail1])
AS "
MySQL = MySQL & "ProductLin e, Mid(Trim([ProductLine]),13,3) AS ProdLine,
RPT086.ID "
MySQL = MySQL & "FROM RPT086 "
MySQL = MySQL & "WHERE (((StripSpaces([PartNumber1] & [PerCar1] &
[Retail1])) Like '*' "
MySQL = MySQL & "& "
MySQL = MySQL & Chr$(34) & "ProductLin e"
MySQL = MySQL & Chr$(34) & " & '*')) "
MySQL = MySQL & "ORDER BY RPT086.ID;"
'Debug.Print MySQL

'************** ************* FILL IN LINE CODES *************** ************
Me![txtProgress].Text = "Adding line codes to all records."
Me.Refresh
DoCmd.Beep
Me![txtProgress].SelStart = 0
Wait 2, False
Set MyDB = CurrentDb

Dim rstLines As Recordset
Set rstLines = MyDB.OpenRecord set(MySQL)

With rstLines
.MoveLast
.MoveFirst
MyRecCount = .RecordCount

For intI = 1 To MyRecCount
MyLine = !Prodline
MyFirstID = !ID
.MoveNext

If Not .EOF Then
MyNextID = !ID
MyLastID = MyNextID - 1
fSetLines086 'call the function
Else
.MoveLast
MyLastID = !ID
fSetLines086 'call the function
End If

Next intI

.Close
End With
Set MyDB = Nothing

'============== ========== Step 7 =============== ===========
'============== ======= Delete the CRAP =============== =====
Me![txtProgress].Text = "Deleting non-valuable data."
Me.Refresh
DoCmd.Beep
Me![txtProgress].SelStart = 0
Wait 2, False
MySQL = "" 'Initialize String to nothing.
MySQL = MySQL & "DELETE IIf(IsNumeric([Cost1]),CCur([Cost1]),0) AS Expr1, "
MySQL = MySQL & "RPT086.Lin e1, RPT086.PartNumb er1, RPT086.PerCar1, "
MySQL = MySQL & "RPT086.Retail1 , RPT086.Cost1, RPT086.Core1, "
MySQL = MySQL & "RPT086.Descrip tion1 FROM RPT086 WHERE "
MySQL = MySQL & "(((IIf(IsNumer ic([Cost1]),CCur([Cost1]),0))=0)); "

DoCmd.SetWarnin gs False
DoCmd.RunSQL (MySQL)
DoCmd.SetWarnin gs True

Me![txtProgress].Text = "Deletion of non-valuable data complete."
Me.Refresh
DoCmd.Beep
Me![txtProgress].SelStart = 0
Wait 2, False
'============== ========== Step 8 =============== ===========
'============== Check for Blank Line Codes ===============
' We need to ensure ALL PartNumbers have Line Codes before
' updating the Inventory table, or updates will get missed!

Dim CountBlanks As Integer
CountBlanks = DCount("PartNum ber1", "RPT086", "IsNull([Line1])") +
DCount("PartNum ber2", "RPT086", "IsNull([Line2])")
If CountBlanks 0 Then
Msg = ""
Msg = Msg & "The pricing table contains "
Msg = Msg & CountBlanks
Msg = Msg & " part numbers that do not have a line code." & CR & CR
Msg = Msg & "A form will open to allow you to fill these in"
Msg = Msg & "before updating the inventory table."
MsgBox (Msg)

'Open the form modally...i.e, after the form is closed,
'control will be returned to this procedure
DoCmd.OpenForm "frmUpdateLineC ode086", , , , , acDialog
Me.Repaint

End If

Me![txtProgress].Text = "Line codes have been added successfully."
Me.Refresh
DoCmd.Beep
Me![txtProgress].SelStart = 0
Wait 2, False

'============== ========== Step 9 =============== ===========
'============== === Merge Data to tblPricing ===============
Me![txtProgress].Text = "Merging imported 2-column data to a single-column
master pricing table."
Me.Refresh
DoCmd.Beep
Me![txtProgress].SelStart = 0
Wait 2, False

'Left side of RPT086
MySQL = "" 'Initialize String to nothing.
MySQL = MySQL & "INSERT INTO tblPricing ( Line, PartNumber, PerCar, Retail,
Cost, "
MySQL = MySQL & "Core, Description, PriceDate ) "
MySQL = MySQL & "SELECT RPT086.Line1, Trim([PartNumber1]) AS Expr1, "
MySQL = MySQL & "RPT086.PerCar1 , CCur([Retail1]) AS Expr2, CCur([Cost1]) AS
Expr3, "
MySQL = MySQL & "CCur(Nz([Core1],0)) AS Expr4, Trim([Description1]) AS
Expr5,RPT086.Rp tDate "
MySQL = MySQL & "FROM RPT086; "

DoCmd.SetWarnin gs False
DoCmd.RunSQL (MySQL)
DoCmd.SetWarnin gs True

'Right side of RPT086
MySQL = "" 'Initialize String to nothing.
MySQL = MySQL & "INSERT INTO tblPricing ( Line, PartNumber, PerCar, Retail,
Cost, "
MySQL = MySQL & "Core, Description, PriceDate ) "
MySQL = MySQL & "SELECT RPT086.Line2, Trim([PartNumber2]) AS Expr1, "
MySQL = MySQL & "RPT086.PerCar2 , CCur([Retail2]) AS Expr2, CCur([Cost2]) AS
Expr3, "
MySQL = MySQL & "CCur(Nz([Core2],0)) AS Expr4, Trim([Description2]) AS
Expr5,RPT086.Rp tDate "
MySQL = MySQL & "FROM RPT086; "

DoCmd.SetWarnin gs False
DoCmd.RunSQL (MySQL)
DoCmd.SetWarnin gs True

EliminateDupes0 86 ' Call the function

'Get rid of empty part numbers from 2nd column.
MySQL = "" 'Initialize String to nothing.
MySQL = MySQL & "Delete tblPricing.Part Number, tblPricing.id FROM tblPricing
WHERE "
MySQL = MySQL & "(((tblPricing. PartNumber) Is Null)); "

DoCmd.SetWarnin gs False
DoCmd.RunSQL (MySQL)
DoCmd.SetWarnin gs True

'============== ========== Step 10 =============== ===========
'============== == Update Inventory Pricing =============== =

Me![txtProgress].Text = "Revising Prices in Inventory table."
Me![txtProgress].SelStart = 0
Wait 2, False

MySQL = "" 'Initialize String to nothing.
MySQL = MySQL & "UPDATE tblPartsInvento ry INNER JOIN tblPricing ON"
MySQL = MySQL & "(tblPartsInven tory.Line = tblPricing.Line ) AND"
MySQL = MySQL & "(tblPartsInven tory.PartNumber = tblPricing.Part Number)"
MySQL = MySQL & " SET tblPartsInvento ry.Retail = [tblPricing]![Retail], "
MySQL = MySQL & "tblPartsInvent ory.Cost = [tblPricing]![Cost],"
MySQL = MySQL & " tblPartsInvento ry.PriceDate = [tblPricing]![PriceDate];"
'UPDATE tblPartsInvento ry INNER JOIN tblPricing ON
tblPartsInvento ry.PartNumber
'= tblPricing.Part Number SET tblPartsInvento ry.Retail =
[tblPricing]![Retail],
'tblPartsInvent ory.Cost = [tblPricing]![Cost], tblPartsInvento ry.PriceDate =
[tblPricing]![PriceDate];
'Debug.Print MySQL

DoCmd.SetWarnin gs False
DoCmd.RunSQL (MySQL)
DoCmd.SetWarnin gs True

Me![sbfPriceDates].Form.Requery
Me![sbfPriceDates].SetFocus
DoCmd.GoToRecor d , , acLast

Me![txtProgress].SetFocus
Me![txtProgress].Text = "Data import and conversion process completed."
Me![txtProgress].SelStart = 0
Wait 2, False

Me![txtProgress].SetFocus
Me![txtProgress].Text = ""
Me![sbfPriceDates].SetFocus
Me![txtProgress].Visible = False
' then open the dialog box / report.
cmdImport086_Ex it:
Exit Sub

cmdImport086_Er r:
MsgBox Error$

Resume cmdImport086_Ex it

End Sub

"Bob" <sc*******@colo nialfirststate. com.auwrote in message
news:11******** **************@ e65g2000hsc.goo glegroups.com.. .
Hi all,

I've got a table that I've imported and it has junk at the top of the
table, so after import I run a delete query to remove the junk lines
then I'm left with the field names I want for the table at the top of
the table but the field names currently are 'field1' etc, so how do I
rename the field names to the fields on the top row of the table.

Cheers,

Bob

Mar 24 '07 #5

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

Similar topics

1
3905
by: Earl Anderson | last post by:
I have imported an Excel worksheet into A97/WinXPH which had the new employees names in one field ( in a Last Name,First Name configuration). I wanted to split that one field ( ) into two fields ( & ). The table I imported, , contains 61 records with a PK of . Using the Query Grid, I constructed the following query (SQL View here) to...
3
18505
by: Tom | last post by:
Data is collected over time in an Excel worksheet with 20 columns. The Excel worksheet starts out as a copy of a template as is filled in as data is collected. Eventually the worksheet file is saved and an Access table is linked to the Excel worksheet. Different people collect the data in the Excel worksheet than who use the database. The...
2
2905
by: Ralph | last post by:
I'm trying to import a range of cells from an Excel spreadsheet into a table in access. The first row contains column labels, but I cannot use those as my field names, both because of their format (number, space, text) and because I've got a whole bunch of similar tables and I need to have consistant field names in these tables for some data...
5
2355
by: Geoff Portbury | last post by:
I'm a swimming club coach. I have a data base for recording times at various meets. I have a FORM for entering times called SWIM TIMES. When I enter the swimmers name ID, eg FOR01 for Doug Ford I want "Doug" to populate the FIRST Name field and "Ford" to populate the Last Name field. At present I have to manually enter them. I have a table...
18
18328
by: Dixie | last post by:
Can I set the Format property in a date/time field in code? Can I set the Input Mask in a date/time field in code? Can I set the Format of a Yes/No field to Checkbox in code? I am working on a remote update of tables and fields and can't find enough information on these things. Also, how do you index a field in code?
3
9382
by: Oliver Gabriel | last post by:
Hi, i want to export a table for later import, using vba. That´s my code: export: filename = "C:\HVOtabelle.txt"
5
4232
by: HS1 | last post by:
Hello I have a datagrid to show data for a database table using "seclect * from tablename" The datagrid works OK. However, I want to change the name of the fields in the database to other name in DataGrid. For example, a field name in database is "FName" will be shown in dataGrid as "First Name". Could you please tell me how to do that
9
3100
by: sellcraig | last post by:
Microsoft access 2 tables table "data main" contains a field called "code" table "ddw1" is created from a make table query of "data main" Goal- the data in "code" field in needs to be inserted into a standard web address in the table (the filed name is link) in ddw1 Example address ---
11
10277
by: Tim Hunter | last post by:
Hi I am using WinXP and Access 2003 Is it possible to store the field names of a table in an array and then loop through the array and update the table using the field names stored in the array? I can't figure out the coding to accomplish this. I have an Excel application that is a monster and it has become too much to maintain and test. I...
0
7435
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7694
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7792
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6026
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5360
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5080
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3470
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1921
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1046
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.