I have been trying to figure out a way to run the following VBA code on all of the files I have in a folder without having to manually open each file.
This is the code I have right now (exports the desired table as a delimited txt file, including column names):
Private Sub Command4_Click()
Dim MyObj, MySource As Object, File As Variant, stDocName As String, Counter As Integer
On Error GoTo Err_Command4_Click
Dim stDocName As String, Counter As Integer
Counter = 1
stDocName = "tblSCTurCount"
DoCmd.TransferText acExportDelim, "", stDocName, "C:\Users\name\Downloads\cnt\cnt_output.txt", True
Exit_Command4_Click:
Exit Sub
Err_Command4_Click:
MsgBox Err.Description
Resume Exit_Command4_Click
End Sub
When researching the problem, I found a process that works in excel, but I'm not sure how to do the variables change in access, especially the workbook references.
Thank you!
EDIT -- Code that worked:
Dim FS As FileSystemObject
Set FS = New FileSystemObject
Dim MyFolder As Folder
Set MyFolder = FS.GetFolder("C:\Users\name\Downloads\cnt\Folder")
Dim MyFile As File
Set appAccess = CreateObject("Access.Application")
For Each MyFile In MyFolder.Files
appAccess.OpenCurrentDatabase (MyFile.Path)
appAccess.Visible = True
NewFileName = MyFile.Path & ".txt"
appAccess.DoCmd.TransferText acExportDelim, "", "tblScTurCount", NewFileName, True
appAccess.CloseCurrentDatabase
Next
Consider using the FileSystemObject.
For that you will have to add a reference the Microsoft Scripting Runtime library. (Go to tools > references... in the VBA editor)
Sub test()
Dim FS As FileSystemObject
Set FS = New FileSystemObject
Dim MyFolder As Folder
Set MyFolder = FS.GetFolder("C:\path\of\the\folder")
Dim MyFile As File
For Each MyFile In MyFolder.Files
'do what you want to do with each file
'to use the file name:
MyFile.Name
'I suppose you have to:
Application.OpenCurrentDatabase MyFile.Path
'(please verify if this path contains the filename and extension too).
'But create a different filename for each txt:
NewFileName = MyFile.Path + ".txt"
'Then you do:
DoCmd.TransferText acExportDelim, "", "tblScTurCount", NewFileName, True
Next
End Sub
Considering you are using VBA in Access, use the Application.OpenAccessProject or the Application.OpenCurrentDatabase methods to open files in Access.
Related
Thank you for taking the time to read this.
I am trying to use the LIKE operator to open workbooks. Previously I went with this code which works really well
Report_Name = "\XYZ.xls"
Workbooks.open Filename:= ThisWorkbook.Path & Report_Name
My main goal is to essentially open a report and sometimes the names differ i.e healthdoc or healthassess
I tried utilizing the LIKE operator to pick up on the name of the workbook however I cannot find a way to code it.
Any direction or help is appreciated. Thank you!
I was trying to use this syntax
Dim Report_Name as Workbook
if Report_Name LIKE "*Health*" then
xyz
else
xyz
However I could only get LIKE operator working only with strings
Use FSO to loop through files and check their names:
Option Explicit
Sub Example()
Dim WB As Workbook
Dim FSO As New FileSystemObject
Dim oFolder As Object
Dim oFile As Object
Set FSO = CreateObject("Scripting.filesystemobject")
Set oFolder = FSO.GetFolder("C:\Users\cameron\Documents")
For Each oFile In oFolder.Files
If oFile.Name Like "*Your Partial File Name*" Then
Set WB = Workbooks.Open(oFile.Path)
'Do whatever you want with your workbook.
WB.Close '(Optional True/False for save changes)
End If
Next oFile
End Sub
Here are 2 sub that I can suggest. Since I don't understand from your question if you want to loop, open and modify the files in a folder, or you want simply to check the files names in a folder, I made 2 sub. One "LoopFilesNamesInFolder" will loop to check the file names without opening the files, and second one "LoopAndOpenFilesInFolder" allows you to open and make changes if you want to the files. You can use any of them based on your needs. Let me know if it helps you
Public Sub LoopFilesNamesInFolder()
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim MyFileName As String
myPath = ThisWorkbook.Path & "\"
'The file name that you are looking for
MyFileName = "*Health*"
myExtension = "*.xls*"
'Current File in loop
myFile = Dir(myPath & myExtension)
Do While myFile <> vbNullString
If myFile Like MyFileName Then
'You can also use something like
'If LCase(myFile) Like LCase(MyFileName) Then
'If you want to make it not case sensitive
'Your code
Else
'Your code
End If
'Get next file name
myFile = Dir
Loop
End Sub
Public Sub LoopAndOpenFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim MyFileName As String
'if you want to Optimize code keep the following 3 instructions
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
myPath = ThisWorkbook.Path & "\"
'The file name that you are looking for
MyFileName = "*Health*"
myExtension = "*.xls*"
'Current File in loop
myFile = Dir(myPath & myExtension)
Do While myFile <> vbNullString
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'You can add a DoEvents here to give time to Excel to open the workbook before moving fwd
DoEvents
'Do Whatever you want to do
If wb.Name Like MyFileName Then
'You can also use something like
'If LCase(wb.Name) Like LCase(MyFileName) Then
'If you want to make it not case sensitive
'Your Code
Else
'Your Code
End If
'If you want to save your changes, replace the False by True to Save and Close Workbook
wb.Close SaveChanges:=False
'You can add a DoEvents here as well to give time to your Excel to close before moving to next one
DoEvents
'Get next file name
myFile = Dir
Loop
'Reset Settings
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
End Sub
I’m trying to make VBA script for Access 2013 which will help to process Word 2013 forms from folder, attach these files of Word 2013 form to relevant record entry and attach pdf file from same folder with the same name.
Since I’m not a programmer each try leads me to next error.
Can anyone help to make it work.
Thanks.
This code does task of collecting data from files .docx in folder.
Then not to keep files in folder I would like to save them in DB by the proper record.
How to add code that will attach pdf and docx file to the relevant record, assuming that filename of docx and pdf is the same?
I need a clue how to incert it to relevant record or start new part of script. what commands can be used and in what place to start new part of script?
Private Sub ImportFormdata_Click()
Dim appWord As Word.Application
Dim doc As Word.Document
Dim SourceFolderPath As String
Dim FormFile As String
Dim strName As String
Dim rst As DAO.Recordset
SourceFolderPath = CurrentProject.Path & "\"
FormFile = Dir(SourceFolderPath & "*.docx", vbNormal)
Do While FormFile <> ""
Set appWord = CreateObject("Word.Application")
strName = SourceFolderPath & FormFile
Set doc = appWord.Documents.Open(strName)
appWord.Visible = False
Set rst = CurrentDb.OpenRecordset("FormData")
With rst
.AddNew
![Question1] = doc.FormFields("Q1").result
![Question2] = doc.FormFields("Q2").result
![Question3] = doc.FormFields("Q3").result
![File name] = FormFile
.Update
.Close
End With
doc.Close
appWord.Quit
FormFile = Dir
Loop
MsgBox "Forms imported!"
End Sub
I am creating an MS Access 2010 database. I am using the API to do what the common dialog control did in previous versions of MS Access to open a directory and select a file. My client would like me to be able to open all of the files in the directory when a user clicks on a folder (so the user does not click on a file, just a folder). I cannot find an even triggering when the folder is clicked on within the common dialog control that comes up using the API.
Can anyone tell me how to open all the files in a directory (they will be .pdf files) when using the API for the common dialog control in MS ACCESS 2010?
The API calls I am using are here: http://access.mvps.org/access/api/api0001.htm
Use a FileSystemObject from Microsoft.Scripting.Runtime (must add reference to the project).
The following sub adds to a collection the string names of all pdf files in a given folder.
Get the folder path from the dialog (with folder picking option, not file picking)
Sub GetFolderPDFFiles(FolderPath As String, Col As Collection)
Dim FS As New FileSystemObject
Dim Dir As Folder
Dim Arq As File
Set Dir = FS.GetFolder(FolderPath)
For Each Arq In Dir.Files
If UCase(Right(Arq.Name, 4)) = ".PDF" Then
Call Col.Add(Arq.Path)
End If
Next
End Sub
This worked great for me... it will promt the dialog box to select the folder and open the .pdf files. it will also list all the files in Table1.
Option Compare Database
'function to select the folder where the files are:
Function ChooseFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
ChooseFolder = sItem
Set fldr = Nothing
End Function
Enter the routines to open and list the pdf files in the folder (it also look for files in subfolders):
Sub Open_List_Files()
'Declare the variables
Dim objFSO As Scripting.FileSystemObject
Dim objFolder, objTopFolder As Scripting.Folder
Dim strTopFolderName As String, ProjectF As String
Dim i As Long
' call the function to select the folder
Call Módulo1.ChooseFolder
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the top folder
Set objTopFolder = objFSO.GetFolder(ChooseFolder)
'Call the RecursiveFolder routine
Call RecursiveFolder(objTopFolder, True)
End Sub
Sub RecursiveFolder(objFolder As Scripting.Folder, IncludeSubFolders As Boolean)
'Declare the variables
Dim objFile As Object
Dim objSubFolder As Scripting.Folder
Dim DBStr, filepath As String
'Loop through each file in the folder
For Each objFile In objFolder.Files
On Error Resume Next
If InStr(objFile.Name, ".pdf") Then
DBStr = "INSERT INTO Table1 ([File Name]) " & _
" VALUES (" & _
"'" & objFile.Name & "', " & "');"
CurrentDb.Execute DBStr
'open the file
Application.FollowHyperlink objFile
End If
Next objFile
'Loop through files in the subfolders
If IncludeSubFolders Then
For Each objSubFolder In objFolder.SubFolders
Call RecursiveFolder(objSubFolder, True)
Next objSubFolder
End If
End Sub
Run the Open_List_Files() Macro and there you go! :)
At work we have a split ms access database. The backend lies on a drive that is mapped locally (so for everyone it's the same path). I know want to create a button in the frontend that when clicked automatically creates a merged version of the database. This version is necessary for out specific backup/history needs. I have very little knowledge of VBA programming, so any help is appreciated.
To create the merged version the code should just execute the following:
Create duplicate frontend (?)
Delete all existing tables in the duplicate
Import tables from the backend into the duplicate
(I am aware that it is not such a good idea to merge split databases, but in this case with many users that have absolutely no knowledge of CS it is the most usable solution)
Create a Module in the front-end database with the following Function
Public Function ImportLinkedTables()
Dim cdb As DAO.Database, tbd As DAO.TableDef
Dim tablesToLink As Collection, item As Variant, a() As String
Const LinkPrefix = ";DATABASE="
Set cdb = CurrentDb
Set tablesToLink = New Collection
For Each tbd In cdb.TableDefs
If tbd.Connect Like (LinkPrefix & "*") Then
'' tab-delimited list: TableDef name [tab] Source file [tab] Source table
tablesToLink.Add tbd.Name & vbTab & Mid(tbd.Connect, Len(LinkPrefix) + 1) & vbTab & tbd.SourceTableName
End If
Next
Set tbd = Nothing
For Each item In tablesToLink
a = Split(item, vbTab, -1, vbBinaryCompare)
DoCmd.DeleteObject acTable, a(0)
Debug.Print "Importing [" & a(0) & "]"
DoCmd.TransferDatabase acImport, "Microsoft Access", a(1), acTable, a(2), a(0), False
Next
Set tablesToLink = Nothing
Set cdb = Nothing
DoCmd.Quit
End Function
Create a Macro named "ImportLinkedTables" with a single step:
RunCode
Function Name ImportLinkedTables()
The code behind the form button to kick off the process would be
Private Sub Command0_Click()
Dim fso As FileSystemObject
Dim wshShell As wshShell
Dim accdbName As String, command As String
Const SourceFolder = "Y:\_dev\"
Const DestFolder = "C:\Users\Gord\Desktop\"
accdbName = Application.CurrentProject.Name
'' copy front-end file to new location
Set fso = New FileSystemObject
fso.CopyFile SourceFolder & accdbName, DestFolder & accdbName, True
Set fso = Nothing
Set wshShell = New wshShell
command = """"
command = command & wshShell.RegRead("HKLM\Software\Microsoft\Office\" & Application.Version & "\Common\InstallRoot\Path")
command = command & "MSACCESS.EXE"" """ & DestFolder & accdbName & """ /x ImportLinkedTables"
wshShell.Run command, 7, False
Set wshShell = Nothing
End Sub
I have a large amount of csv files that I need in .xls format. Is it possible to run a batch conversion with a macro or best done with another language?
I have used this code http://www.ozgrid.com/forum/showthread.php?t=71409&p=369573#post369573 to reference my directory but I'm not sure of the command to open each file and save them. Here's what I have:
Sub batchconvertcsvxls()
Dim wb As Workbook
Dim CSVCount As Integer
Dim myVar As String
myVar = FileList("C:\Documents and Settings\alistairw\My Documents\csvxlstest")
For i = LBound(myVar) To UBound(myVar)
With wb
Application.Workbooks.OpenText 'How do I reference the myvar string ?
wb.SaveAs '....
End With
Next
End Sub
Function FileList(fldr As String, Optional fltr As String = "*.*") As Variant
Dim sTemp As String, sHldr As String
If Right$(fldr, 1) <> "\" Then fldr = fldr & "\"
sTemp = Dir(fldr & fltr)
If sTemp = "" Then
FileList = Split("No files found", "|") 'ensures an array is returned
Exit Function
End If
Do
sHldr = Dir
If sHldr = "" Then Exit Do
sTemp = sTemp & "|" & sHldr
Loop
FileList = Split(sTemp, "|")
End Function
Edit: The files are .txt files formatted as csv
By combining the code given by Scott Holtzman and 'ExcelFreak', the conversion works quite well. The final code looks something like this:
Sub CSV_to_XLS()
Dim wb As Workbook
Dim strFile As String, strDir As String
strDir = "U:\path\"
strFile = Dir(strDir & "*.csv")
Do While strFile <> ""
Set wb = Workbooks.Open(Filename:=strDir & strFile, Local:=True)
wb.SaveAs Replace(wb.FullName, ".csv", ".xls"), 50 'UPDATE:
wb.Close True
Set wb = Nothing
strFile = Dir
Loop
End Sub
Opening the converted .xls file throws a warning everytime:
"The file you are trying to open, 'filename', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?"
Clicking Yes then opens the .xls file.
Is there a way to get rid of this warning message? Excel throws a warning everytime the .xls file is opened.
In a lot less lines of code, this should get you what you want. However, I will say this may not be the fastest way to get it done, because you are opening, saving, and closing the workbook every time. I will look for a faster way, but I forget the method off the top of my head.
Sub batchconvertcsvxls()
Dim wb As Workbook
Dim strFile As String, strDir As String
strDir = "C:\"
strFile = Dir(strDir & "*.csv")
Do While strFile <> ""
Set wb = Workbooks.Open(strDir & strFile)
With wb
.SaveAs Replace(wb.FullName, ".csv", ".xls"), 50 'UPDATE:
.Close True
End With
Set wb = Nothing
Loop
End Sub
** UPDATE **
you need the proper fileformat enumeration for a .xls file. I think its 50, but you can check here Excel File Type Enumeration, if it's not.
The Code of Scott Holtzman nearly did it for me. I had to make two changes to get it to work:
He forgot to add the line that makes our loop continue with the next file. The last line before the Loop should read
strFile = Dir
The Workbooks.Open method did not read my CSV files as expected (the whole line ended up to be text in the first cell). When I added the parameter Local:=True it worked:
Set wb = Workbooks.Open(Filename:=strDir & strFile, Local:=True)
This works properly at least on Excel 2013. Using FileFormat:=xlExcel8 parameter instead of the filetype tag 50 creates files that open without security nags.
Sub CSV_to_XLS()
Dim wb As Workbook
Dim strFile As String, strDir As String
strDir = "C:\temp\"
strFile = Dir(strDir & "*.csv")
Do While strFile <> ""
Set wb = Workbooks.Open(Filename:=strDir & strFile, Local:=True)
wb.SaveAs Replace(wb.FullName, ".csv", ".xls"), FileFormat:=xlExcel8
wb.Close True
Set wb = Nothing
strFile = Dir
Loop
End Sub
This was a good question and I have found in the internet several answers. Just making very small changes (I couldn't edit any of the codes already published) I could make things work a bit better:
Sub CSV_to_XLSX()
Dim wb As Workbook
Dim strFile As String, strDir As String
strDir = "C:\Users\acer\OneDrive\Doctorado\Study 1\data\Retest Bkp\Day 1\Sart\"
strFile = Dir(strDir & "*.csv")
Do While strFile <> ""
Set wb = Workbooks.Open(Filename:=strDir & strFile, Local:=True)
With wb
.SaveAs Replace(wb.FullName, ".csv", ".xlsx"), 51
.Close True
End With
Set wb = Nothing
strFile = Dir
Loop
End Sub