Mofongo
Mofongo

Reputation: 131

How to loop through MS Access tables using Python

from win32com.client import Dispatch

oAccess = Dispatch("Access.Application")
oAccess.Visible = False
oAccess.OpenCurrentDatabase(my_db)
oDB = oAccess.CurrentDB

for tbl in oDB.TableDefs:
     print(table.Name)
     tbl.RefreshLink

I've also done:

for tbl in oAccess.TableDefs:
     print(table.Name)
     tbl.RefreshLink

Error: 'function' object has no attribute 'TableDefs'

I'm starting to understand how to manipulate Windows using win32com, but for some reason it seems like ".TableDefs" isn't recognized. Am I going about it the wrong way?

I know this can be done in VBA. I've been tasked with switching everything over to Python.

Upvotes: 0

Views: 263

Answers (1)

Erik A
Erik A

Reputation: 32642

Your first error, here, is that VBA knows CurrentDb is a method, and can't assign a method to a variable, so it invokes the method.

Python, however, has 0 problems with assigning a method to a variable, so just does so. Which means you need the parentheses to invoke the method:

oDB = oAccess.CurrentDb()

This fixes the immediate issue (same goes for tbl.RefreshLink, this likely should be tbl.RefreshLink()).

Furthermore, you never define table, only tbl, so you likely want print(tbl.Name).

Upvotes: 2

Related Questions