views:

122

answers:

2

I´m trying to rename an Access Table using VBA from Excel... any help?

+4  A: 

How about:

Dim appAccess As Object
''acTable=0

Set appAccess = CreateObject("Access.Application")
appAccess.OpenCurrentDatabase "C:\Docs\LTD.mdb"

appAccess.DoCmd.Rename "NewTableName", 0, "OldTableName"

appAccess.Quit
Set appAccess = Nothing
Remou
It would be nice if your code cleaned up after itself, don't you think?
David-W-Fenton
@David W Fenton I was under the impression that this was a forum where ideas should be enough, for the most part and that even one-line answers would suffice.
Remou
@David W Fenton if you really think it is that important, edit the answer and fix it yourself
Christian Payne
+6  A: 

Here's an example from one of my programs (which still is in daily use at the company). It's taken from a vb6 program, but also executes in vba. I've tested it to be sure.

In this example we have a temporary table with the name "mytable_tmp", which is updated with new data and we'd like to save this to the table "mytable" by replacing it.

From your Excel vba editor you'll need to set a reference to the following two type libraries:

  • "Microsoft ActiveX Data Objects 2.8 Library"
  • "Microsoft ADO Ext. 2.8 for DDL and Security"

The first one is for the ADODB namespace and the second for the ADOX namespace. (Maybe you have an earlier version of MDAC like 2.5 or earlier; this should work too).

Private Sub RenameTable()
Dim cn         As New ADODB.Connection
Dim cat        As ADOX.Catalog
Const sDBFile  As String = "c:\et\dbtest.mdb"

   On Error GoTo ErrH

   With cn
      .Provider = "Microsoft.Jet.OLEDB.4.0"
      .Mode = adModeShareDenyNone
      .Properties("User ID") = "admin"
      .Properties("Password") = ""
      .Open sDBFile
   End With

   Set cat = New ADOX.Catalog
   cat.ActiveConnection = cn
   cat.Tables("mytable").Name = "mytable_old"
   cat.Tables("mytable_tmp").Name = "mytable"
   cat.Tables("mytable_old").Name = "mytable_tmp"

ExitHere:
   If Not cn Is Nothing Then
      If Not cn.State = adStateClosed Then cn.Close
      Set cn = Nothing
   End If
   Set cat = Nothing
   Exit Sub

ErrH:
Dim sMsg As String
   sMsg = "Massive problem over here man."
   sMsg = sMsg & vbCrLf & "Description : " & cn.Errors.Item(0).Description
   MsgBox sMsg, vbExclamation
   GoTo ExitHere
End Sub

Hoping to be helpful.

_pointer
It seems to me that the only value of this longwinded code over Remou's three lines of code is for when you don't have Access installed.
David-W-Fenton
It also gives the option of doing more than just a straight copy within the same code - and who knows, the Excel user might not have access to Access. Still, in general I have to agree Remou's looks more usable.
mavnn
;) How dare you include error handling and user messages. And what's all that formatting about! (Much funnier if you do it in the voice of Stewie). +1
Jeff O