I have a slew of files that I need exported into Access. I'm using the following code to import all .txt files within the folder in a table in Access. I needed to use a custom Import Spec due to the presence of colons in some of the files which Access kept trying to treat as time.
Option Compare Database
Private Sub Command0_Click()
Dim fso As Object
Dim fld As Object
Dim fil As Object
Dim FldPath As String
Dim MyResult As String
Const DestTable As String = "Splits"
FldPath = "C:\Users\User\Desktop\yahoo\yahoo_splits"
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder(FldPath)
With DoCmd
.SetWarnings False
For Each fil In fld.Files
If UCase(Right(fil.Name, 3)) = "txt" Then
MsgBox (fil.Path)
DoCmd.TransferText acImportDelim, "SPTImport", "Splits", fil.Path, False
CurrentDb.Execute ("Update Splits Set MyNewField = '" & fil.Name & "' where MyNewField is null")
End If
Next
.SetWarnings True
End With
Set fil = Nothing
Set fld = Nothing
Set fso = Nothing
MsgBox "done"
End Sub
When I try to import the file, I get the error:
The Microsoft Access database engine could not find the object 'Fox.spt.txt'. Make sure the object exists and that you spell its name and the path name correctly.
What is odd is that I even added the message box prompt just before the import step so that I could verify that it is calling the right path before it gets to the code that errors out.
Any help would be greatly appreciated!
Related
I am attempting to create an access table containing the index information for around 548,000 images. Currently, the index information is contained in around 525 .txt files. I have found that I can accurately import this information into access via external data -> import new data. The .txt files are uniformly formatted with column names in the first row, and the respective attributes delimited by "|". I suppose what I'm asking for, is help creating a macro that will iterate through this folder, and import each of these .txt files into a single table that I can then use to search for the corresponding image. Here's a VBA I used to previously iterate through a folder of .dbf files. How might I use this to iterate through .txt files delimited by "|"
Option Compare Database
Private Sub ImportDBF()
On Error GoTo ErrHandler 'change to On Error GoTo ErrHandler if you want to see errors.
Dim oFSystem As Object
Dim oFolder As Object
Dim oFile As Object
Dim sFolderPath As String
Dim i As Integer
sFolderPath = "C:\Users\Juan Rodriguez\Desktop\Well data headers"
Set oFSystem = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSystem.getfolder(sFolderPath)
For Each oFile In oFolder.Files
If Right(oFile.Name, 3) = "dbf" Then
SQL = "INSERT INTO complete_db SELECT * FROM [" & oFile.Name & "]" _
& " IN '" & sFolderPath & "'[dBASE IV;]"
CurrentDb.Execute SQL
End If
Next oFile
Exit Sub
ErrHandler:
MsgBox Err.Description
End Sub
I have attached some images containing the filepath for the .txt files as well as the filepath for the images. The images are in various subdirectories.image1image2
Any insight is greatly appreciated! Thank you in advance!
I am trying to scrape a directory for all the files in it, and only attach the most recently modified file.
I have code that will attach files.
I started off with code that is essentially like this
Dim JobLocation As String
JobLocation = InputBox("What is the Clients Name ?")
ClientDirectory = "S:\Client Folder\" & JobLocation & "\Site Drawings\"
RequiredPDFs = Dir(ClientDirectory & "*.pdf")
Do While Len(RequiredPDFs) > 0
.Attachments.Add ClientDirectory & RequiredPDFs
RequiredPDFs = Dir
Loop
I want to adapt the code to find the file that was last modified and only attach that file.
Sub Test()
Dim JobLocation As String
Dim objFile As Object
Dim dLastModifiedDate As Date
Dim strLastModifiedFilePath As String
Dim objMail As Outlook.MailItem
Dim ClientDirectory As Object
JobLocation = InputBox("What is the Clients Name ?")
ClientDirectory = "S:\Client Folder\" & JobLocation & "\Site Drawings\"
If ClientDirectory.Files.Count > 0 Then
For Each objFile In ClientDirectory.Files
If (objFile.DateLastModified > dLastModifiedDate) Then
strLastModifiedFilePath = objFile.Path
dLastModifiedDate = objFile.DateLastModified
End If
Next
If strLastModifiedFilePath <> "" Then
Set objMail = Outlook.Application.ActiveInspector.CurrentItem
objMail.Attachments.Add strLastModifiedFilePath
End If
End If
End Sub
I expected this to crawl through each file, compare it to the next and then attach that which was the LastModified.
It throws the following error:
'Run-time error '91': Object variable or With block variable not set'
You treat variable ClientDirectory as an object but in original code it is a simple string. That is why your line :
ClientDirectory = "S:\Client Folder\" & JobLocation & "\Site Drawings\"
fail.
Also you missed that this variable is used in a Dir operation that store its result in requiredPDFs variable. That is that variable that contains file names.
I am recently working with some data analysis in my project. In my case I need to run a VBA that can automatically read the data from a list of closed excel workbook named from 1-80 by ascending order, in which the data i would like to read is store at cell F7 .
That's how the data set looks like
I try to study the threads on internet and i come up with the following "function". It actually works but it doesn't loop according to ascending order.(1,2,3.....9,10,11.......80) Is the excel treat my file name as String instead of numeric value? If yes, how to troubleshoot sorting problems?
Private Sub test()
Dim fso As Object, FolDir As Object, FileNm As Object, Cnt As Integer
On Error GoTo erfix
Set fso = CreateObject("scripting.filesystemobject")
Set FolDir = fso.GetFolder("D:\Data\FYP")
Application.ScreenUpdating = False
For Each FileNm In FolDir.Files
If FileNm.Name Like "*" & ".xls" & "*" Then
Application.DisplayAlerts = False
UpdateLinks = True
Workbooks.Open Filename:=FileNm
Application.DisplayAlerts = True
Cnt = Cnt + 1
ThisWorkbook.Sheets("Sheet1").Range("A" & Cnt).Value = _
Workbooks(FileNm.Name).Sheets("Sheet1").Range("F" & 7)
Workbooks(FileNm.Name).Close SaveChanges:=False
End If
Next FileNm
Application.ScreenUpdating = True
Set FolDir = Nothing
Set fso = Nothing
Exit Sub
erfix:
On Error GoTo 0
MsgBox "Error"
Application.ScreenUpdating = True
Set FolDir = Nothing
Set fso = Nothing
End Sub
Thank you
I took the code from here and adjusted it
Option Explicit
Function kc_fsoFiles(theFolder, pattern) As Object
Dim rsFSO, objFSO, objFolder, File
Const adInteger = 3
Const adVarChar = 200
'create an ADODB.Recordset and call it rsFSO
Set rsFSO = CreateObject("ADODB.Recordset")
'Open the FSO object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'go get the folder to output it's contents
Set objFolder = objFSO.GetFolder(theFolder)
'create the various rows of the recordset
With rsFSO.Fields
.append "Name", adVarChar, 200
' Field for the "number" part of the file name
.append "DecName", adInteger
End With
rsFSO.Open
'Now let's find all the files in the folder
For Each File In objFolder.Files
'hide any file that begins with the character to exclude
If File.Name Like pattern Then
rsFSO.AddNew
rsFSO("Name") = File.Name
' if the basename is not an integer this will pobably crahs
rsFSO("DecName") = objFSO.getbasename(File.Name)
rsFSO.Update
End If
Next
'Now get rid of the objFSO since we're done with it.
Set objFSO = Nothing
'And finally, let's declare how we want the files
'sorted on the page. In this example, we are sorting
'by DecName
rsFSO.Sort = "DecName ASC "
'Now get out of the objFolder since we're done with it.
Set objFolder = Nothing
'now make sure we are at the beginning of the recordset
'not necessarily needed, but let's do it just to be sure.
rsFSO.MoveFirst
Set kc_fsoFiles = rsFSO
End Function
If you use this function you will get a list of filenames sorted to your needs
Sub TestIt()
'Now let's call the function and open the recordset
'the folder we will be displaying
Dim strFolder:
strFolder = "...your folder here .."
'the actual recordset we will be creating with the kc_fsoFiles function
Dim rsFSO 'now let's call the function and open the recordset
Set rsFSO = kc_fsoFiles(strFolder, "*xlsx*")
'now we'll create a loop and start displaying the folder
'contents with our recordset. Of course, this is just a
'simple example and not very well formatted, i.e., not in
'a table, but it gets the point across on how you can
'ouput the recordset
While Not rsFSO.EOF
Debug.Print rsFSO.Fields("Name").Value
rsFSO.MoveNext
Wend
'finally, close out the recordset
rsFSO.Close
Set rsFSO = Nothing
End Sub
I am stuck with this word VBA and in need of some assistance.I have 160 word documents in a folder and each .doc contains atleast one phrase like 'IO:' I want to copy all the file names that starts after 'IO:' and stop copying when the cursor finds Report Output:. Here is one sample input:
`Step Name: Step 3 – GP00BMDR
Step Description:: GENISYS main batch driver which processes external transactions and internal transactions, updates masters, generates transaction records to the accounting subsystem and produces print files.
File Specification:
Input: 1. GPFTRNW – PHGP.GPFTRNW.TRN.STD.KSDS
2. GPFSCIM – PHGP.GPFSCIM.SCI.KSDS
3. GPFSCSM – PHGP.GPFSCSM.SCS.KSDS
IO: 1. GPFPDGT – PHGP.GPFPDGT.PDG.TRN.KSDS
2. GPFRTXT – PHGP.GPFRTXT.RTX.KSDS
Report Output: Nil`
So I want to copy the .doc name and the file names after IO: and stops when the cursor reaches Report Output: . Here is my script:
Sub Ftp_Step_Details()
'this macro checks for FTP in respective steps and copy and writes in a cell along with the corresponding JCL
Dim wordApplication As Word.Application
Dim wordDocument As Word.Document
Dim flag As String
Dim Folder As String, J As String, FLD As Object
Dim Objfile As Object
Dim objfso As Object
Dim intRow As String
Dim contents As String
flag = True
Dim intResult As Integer
Dim strPath As String
'the dialog is displayed to the user
intResult = Application.FileDialog(msoFileDialogFolderPicker).Show
'checks if user has cancled the dialog
If intResult <> 0 Then
'dispaly message box
strPath = Application.FileDialog( _
msoFileDialogFolderPicker).SelectedItems(1)
End If
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("D:\FILE-LIST\File-List.xlsx")
objExcel.Visible = True
objExcel.Workbooks.Add
objExcel.Cells(1, 1).Value = "Jcl Name"
objExcel.Cells(1, 2).Value = "File Names"
'Folder = "D:\TEST-IO" 'JCL source goes here
Set objfso = CreateObject("Scripting.FileSystemObject")
Set wordApplication = CreateObject("Word.Application")
intRow = 2
'Opening the file in READ mode
Set FLD = objfso.GetFolder(strPath)
For Each file In FLD.Files
Set Objfile = wordApplication.Documents.Open(file)
Do While Not Objfile.AtEndOfStream
contents = Objfile.ReadLine
If contents Like "*IO:" Then
flag = True
End If
If contents Like "*Report Output:*" Then
flag = False
End If
If flag = True Then
objExcel.Cells(intRow, 1).Value = file.Name
objExcel.Cells(intRow, 2).Value = contents3
intRow = intRow + 1
End If
Loop
Next
Objfile.Close
MsgBox "THANK YOU"
End Sub
Now whie testing the code i am getting TYPE MISMATCH in the step Set Objfile = wordApplication.Documents.Open(file) why is that?
Another doubt I have does Readline function works in word VBA as well?
Now whie testing the code i am getting TYPE MISMATCH in the step Set Objfile = wordApplication.Documents.Open(file) why is that?
Because File is type Scripting.File which is an Object, and the Documents.Open method expects a string.
You could try:
Documents.Open(file.Path)
Another doubt I have does Readline function works in word VBA as well?
No, I don't think so.
Im trying to write to a text file using VBA. Here is my code:
DoCmd.SetWarnings False
'Delete all data from the source table
DoCmd.RunSQL "DELETE * FROM tblSource;"
'Run query to fill it
DoCmd.OpenQuery "qryFilltblSource"
' Declare a FileSystemObject.
Dim fso As FileSystemObject
' Create a FileSystemObject.
Set fso = New FileSystemObject
' Declare a TextStream.
Dim stream As TextStream
' Create a TextStream. The true part overwrites a text file it it already exists
Set stream = fso.CreateTextFile("C:\Target Folder", True)
Set rst = CurrentDb.OpenRecordset("tblSource")
Dim i As Integer
i = 1
Do Until rst.EOF = True
stream.WriteLine (rst!i)
i = i + 1
rst.MoveNext
Loop
stream.Close
DoCmd.SetWarnings True
The first error, I'm assuming I'm probably going to get another one, is "Permission Denied." I can't understand this one as I'm an Admin on this machine. I looked at the target folder and I have fill permissions to do what I want to it - but when I view its properties the box for "Read Only" is highlighted - why is this?
Thanks
You will not be permitted to write to C root, so C:\Target Folder\Atextfile.txt
Consider using TransferText:
DoCmd.TransferText acExportDelim, , tblSource, "c:\docs\output.txt", True
Note that you cannot say:
Dim i As Integer
i = 1
Do Until rst.EOF = True
stream.WriteLine (rst!i) <-- i is a record, not a field
i = i + 1
rst.MoveNext
Loop
You need
Do Until rst.EOF
For i=0 to rst.Fields.Count-1
stream.WriteLine rst(i) ''or rst(i) & "" to avoid problems with Null
Next
rst.MoveNext
Loop