Microsoft Access - module to Upload txt file then import to table. - database

I am new in Access been trying this for over 3days now. im tyingin to create a module or anything that when a press a button from a form the module will show a file dialog. get the .txt file and insert it into a table
here is how far i have got
Private Sub FileUpload()
'Requires reference to Microsoft Office 12.0 Object Library.
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Const MyFile = "TXT_Import_Spec" 'change to suit
'Clear listbox contents.
'Me.FileList.RowSource = ""
'Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
'Allow user to make multiple selections in dialog box.
.AllowMultiSelect = False
'Set the title of the dialog box.
.Title = "Please choose FM16 text files"
'Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add ".txt FM16 Files", "*.TXT"
.Show
obJaces
'Import Myfile
DoCmd.TransferText acImportDelim, "TXT_Import_Spec", "DM1", "MyFile", False
'Delete old records from Tbl_Import
'CurrentDb.Execute "DELETE * FROM DM1"
'Add new records to Tbl_Import
CurrentDb.Execute "INSERT INTO DM1 SELECT * FROM MyFile WHERE MyFile.JobNo IN (SELECT MyFile.JobNo FROM MyFile LEFT JOIN Tbl_Import ON MyFile.JobNo = Tbl_Import.JobNo WHERE Tbl_Import.JobNo Is Null)"
'Delete Myfile Table
CurrentDb.Execute "DROP TABLE MyFile"
End With
End Sub
been a stress full week. will appreciate any help.

#DonGeorge I have manage to get the script working please check the script below but the problem is its taking for ever. because the txt file has like 900,000 records.
so what i did to avoid overflow error is the script to show notification in every 100,000 records uploaded. but that takes like 5 mins for a good computer.
Option Compare Database
Sub uploadData()
On Error GoTo 11:
Dim strFile As String
Dim db As DAO.Database
Dim rs1 As DAO.Recordset
Dim cnt As Double
strFile = GetFile
If strFile <> "" Then
Set db = CurrentDb()
Set rs1 = db.OpenRecordset("BM1")
Dim firstLine As Boolean
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFile)
firstLine = False
msg = MsgBox("Do you want to delete all records from BM1 before loading ?", vbCritical + vbYesNo, "Upload File")
If msg = vbYes Then
DoCmd.SetWarnings False
DoCmd.RunSQL "delete * from BM1"
DoCmd.SetWarnings True
End If
Do Until objFile.AtEndOfStream
strEmployee = objFile.ReadLine
If firstLine = True Then
arrEmployee = Split(strEmployee, ",")
If UBound(arrEmployee) = 20 Then
rs1.AddNew
For i = 0 To rs1.Fields.Count - 1
rs1.Fields(i).Value = Replace(arrEmployee(i), """", "")
Next
rs1.Update
End If
Else
firstLine = True
End If
cnt = cnt + 1
If cnt Mod 100000 = 0 Then
MsgBox "Records Added " & cnt
End If
Loop
rs1.Close
MsgBox "Records Upload Completed"
End If
Exit Sub
11:
MsgBox Err.Description
End Sub
Function GetFile() As String
Dim f As Object
Set f = Application.FileDialog(3)
Dim varfile As Variant
f.AllowMultiSelect = False
f.Filters.Clear
f.Filters.Add "Text File", "*.txt"
f.Show
For Each varfile In f.selecteditems
GetFile = varfile
Exit For
Next varfile
End Function

Related

Array not storing object

I take a bunch of .CSV files from a server, open them and save them to another server as .XLSX. My issue is with:
'Get the folder object associated with the directory
Set objPickup = objFSO.GetFolder(pickUp)
Set objDropoff = objFSO.GetFolder(Dropoff)
I keep getting an error and i'm guessing it's because I am pulling in an array pickUp.
Sub ListfilesAndMove()
'List all files in selected folder
Dim objFSO As Object, objPickup As Object, objDropoff As Object, objFile As Object
Dim wb As Workbook, Dropoff As String, pickUp As Variant
Dim LastRowMonthly46 As Long, b As Long, c As Long
Dim ADay As Integer, AMonth As Integer, AYear As Integer, myDate As Date
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim ws As Worksheet: Set ws = ActiveSheet
Dim B3 As Range: Set B3 = ws.Range("B3")
Dim B26 As Range: Set B26 = ws.Range("B26")
Worksheets("Menu").Activate 'Go to worksheet Menu
'Make variable Pickup equal to value of B3
With Application
pickUp = .Transpose(ws.Range(B3, B26))
End With
Dim i As Long
For i = LBound(pickUp) To UBound(pickUp)
Debug.Print pickUp(i)
Next i
Dropoff = ActiveSheet.Range("B28").Value
Worksheets("Report").Activate 'Go to worksheet Report
Worksheets("Report").Visible = True
Worksheets("Menu").Visible = False
'Get the folder object associated with the directory
Set objPickup = objFSO.GetFolder(pickUp)
Set objDropoff = objFSO.GetFolder(Dropoff)
'Set values for cells A1,B1 and C1 and align text
Worksheets("Report").Range("A1").Value = "The files found in " & objPickup.Name & " are:"
Worksheets("Report").Range("A1").VerticalAlignment = xlCenter
Worksheets("Report").Range("A1").HorizontalAlignment = xlLeft
Worksheets("Report").Range("B1").Value = "Processed Yes/No"
Worksheets("Report").Range("B1").HorizontalAlignment = xlCenter
Worksheets("Report").Range("C1").Value = "New File Location"
Worksheets("Report").Range("C1").VerticalAlignment = xlCenter
Worksheets("Report").Range("C1").HorizontalAlignment = xlLeft
'Loop through the Files collection
Application.DisplayAlerts = False
For Each objFile In objPickup.Files
Worksheets("Report").Cells(Worksheets("Report").UsedRange.Rows.Count + 1, 1).Value = objFile.Name
'Open and Save File
Dim Filename As String
Filename = objFile
If Right(Filename, 4) = ".csv" Then
Application.ScreenUpdating = False
Set wb = Application.Workbooks.Open(Filename)
File_name = ActiveWorkbook.Name
File_name2 = ActiveWorkbook.Name
FileLength = Len(File_name2)
File_name2 = Left(File_name2, FileLength - 4)
ActiveWorkbook.ActiveSheet.Name = "Sheet1" 'Rename sheet
With wb 'Save File
'save file to dropoff location
.SaveAs (objDropoff & "\" & File_name2 & ".xlsx"), FileFormat:=xlOpenXMLWorkbook, ConflictResolution:=xlLocalSessionChanges
.Close SaveChanges:=False 'close file
End With
Dim FSO As Object
Set FSO = CreateObject("scripting.filesystemobject")
'Add Processed Comment
Worksheets("Report").Cells(Worksheets("Report").UsedRange.Rows.Count, 2).Value = "Yes"
'Add location of new File
Worksheets("Report").Cells(Worksheets("Report").UsedRange.Rows.Count, 3).Value = objDropoff
Else
Worksheets("Report").Cells(Worksheets("Report").UsedRange.Rows.Count, 2).Value = "No"
End If
Next
Application.DisplayAlerts = True
'Apply wrap text to B1
Worksheets("Report").Range("B1").WrapText = True
Worksheets("Report").Columns("A:C").AutoFit
'Clean up!
Set objPickup = Nothing
Set objDropoff = Nothing
Set objFile = Nothing
Set objFSO = Nothing
End Sub
I'm not sure why all that code is necessary; based on the explanation of what you need to do, you should only need to run two lines of code for each file:
one to open the .CSV:
Workbooks.OpenText "C:\yourPath\yourFile.csv", 65001, 1, , , , True
and one to save as .XLSX:
ActiveWorkbook.SaveAs "C:\yourPath\yourFile.xlsx", xlOpenXMLWorkbook
I don't memorize syntax for rarely used commands like this; instead I let Excel write the code for me using the Macro Recorder. I do the task once and then clean up the code that Excel generates (which resulted in the examples above).
More Information:
MSDN : Workbooks.OpenText Method
MSDN : Workbook.SaveAs Method
MSDN : Recording a Macro to Generate Code
MSDN : Revising Recorded VBA Macros

How to Import New Data from MS Access Front End with SQL Server back end

Hello,
I need to find a way to import new data into a database which comprises of a SQL Server back end and an MS Access 2010 front end with linked tables to the back end, from the front end.
Ideally, this would involve a user clicking a button on a form in the front end and selecting an excel spreadsheet with new data to import, which would then be saved in the back end SQL Server tables.
I have created a vba module in the Excel spreadsheet I want to import. The code is:
Public Function ExcelPicker(Optional strFileName As String, _
Optional ByVal strWindowTitle As String = "Select an excel file") As String
Dim fd As Office.FileDialog
'Set fd = Application.FileDialog(msoFileDialogFolderPicker)
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Title = strWindowTitle
.Filters.Add "All files", "*.*", 1
.Filters.Add "Excel Workbooks", "*.xls;*.xlsx;*.xlsm", 2
.AllowMultiSelect = False
If .Show = -1 Then
FilePicker = (.SelectedItems(1))
Else
FilePicker = vbNullString
End If
End With
Set fd = Nothing
End Function
I have then created an import button on the MS Access 2010 front end, and in the OnClick event I have entered the code:
Private Sub cmdImportFilterResults_Click()
Dim sExcelFile As String
Set sExcelFile = Application.FileDialog(msoFileDialogFilePicker)
'' if sExcelFile is not blank then
'' import the file to MSSQL linked table
If sExcelFile <> "" Then
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "[Database].Table_Result", sExcelFile, True
End If
End Sub
However, when I click on the import button in the front end, nothing is happening. What is wrong in my code or my solution?
Here's a working example:
Private Sub cmdImportFilterResults_Click()
Dim strWindowTitle As String
Dim objDialog As Object
Dim sExcelFile As String
strWindowTitle = "Select an excel file"
Set objDialog = Application.FileDialog(msoFileDialogFilePicker)
With objDialog
.Title = strWindowTitle
.Filters.Add "Excel Workbooks", "*.xls;*.xlsx;*.xlsm", 1
.AllowMultiSelect = False
.Show
If .SelectedItems.Count = 0 Then
MsgBox "No File Selected."
Else
sExcelFile = Dir(.SelectedItems(1))
End If
End With
' if sExcelFile is not blank then
' import the file to MSSQL linked table
If sExcelFile <> "" Then
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "[Database].Table_Result", sExcelFile, True
End If
End Sub

Missing rows when exporting query in MS Access to MS Excel using VBA

I have a query in Ms Access that runs with 227,288 rows. I made a command button which can export the query into Excel. I've searched and found this code
Private Sub Export_Click()
Dim rst As DAO.Recordset
Dim excelApp As Object
Dim sht As Object
Dim fldHeadings As DAO.Field
Set rst = CurrentDb.OpenRecordset("acct file", dbOpenDynaset)
Set excelApp = CreateObject("Excel.Application")
On Error Resume Next
Set Wbk = excelApp.Workbooks.Open(book1)
If Err.Number <> 0 Or Len(book1) = 0 Then
Set Wbk = excelApp.Workbooks.Add
Set sht = Wbk.Worksheets("CSC Landed")
If Len(sheet1) > 0 Then
sht.Name = Left("acct file", 34)
End If
End If
Set sht = Wbk.Worksheets.Add
If Len(sheet1) > 0 Then
sht.Name = Left("acct file", 34)
End If
On Error GoTo 0
excelApp.Visible = True
On Error GoTo Errorhandler
For Each fldHeadings In rst.Fields
excelApp.ActiveCell = fldHeadings.Name
excelApp.ActiveCell.Offset(0, 1).Select
Next
rst.MoveFirst
sht.Range("A2").CopyFromRecordset rst
sht.Range("1:1").Select
excelApp.Selection.Font.Bold = True
With excelApp.Selection
.HorizontalAlignment = -4108
.VerticalAlignment = -4108
.WrapText = False
With .Font
.Name = "Arial"
.Size = 10
End With
End With
excelApp.ActiveSheet.Cells.EntireColumn.AutoFit
With excelApp.ActiveWindow
.FreezePanes = False
.ScrollRow = 1
.ScrollColumn = 1
End With
sht.Rows("2:2").Select
excelApp.ActiveWindow.FreezePanes = True
With sht
.Tab.Color = RGB(255, 0, 0)
.Range("A1").Select
End With
rst.Close
Set rst = Nothing
Exit Sub
Errorhandler:
DoCmd.SetWarnings True
MsgBox Err.Description, vbExclamation, Err.Number
Exit Sub
End Sub
However, when export is done it only exports 496 rows. I've search and tried different attempts, still the rows I'm getting is only 496. I'm also looking into preferences in VB.
I'm very new in Access. I've done several research but still I couldn't do it.
(Posted on behalf of the OP).
I've got it working by
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
"acct file", "C:\Users\user\Desktop\acctfile.xlsx", True
Assuming that you're running the Export_Click code from within Microsoft Access, you can use the following code to invoke the "Output To" action of the DoCmd object:
Private Sub Export_Click()
DoCmd.OutputTo acOutputQuery, "acct file", acFormatXLSX, , True
End Sub

access use FindFirst command with an array

I'm trying to use the FindFirst command in vba for access with an Array, the Array contains usernames, and I want to search through a table and find the ID of each of the usernames in the array. but I keep getting "Compile Error: Type Mismatch" whenever I press the search button on the access form.
Any ideas? - Also does it look like i am passing the array correctly to the next private sub?
The bit that i'm trying to search with the array starts when I create the username() array.
Private Sub createrel_Click()
'declare variables
Dim stDocName As String, db As Database, RS As Recordset, FindPraNumber As String
Dim vary As Variant
Dim Msg As String
Dim Response As Integer
Dim username() As String
Dim varx() As Variant
If IsNull(Me![userlist]) Then
Msg = "Please choose a pra number from the list"
MsgBox Msg, vbCritical, MsgText
DoCmd.GoToControl "userlist"
Exit Sub
End If
If IsNull(Me![folderlist]) Then
Msg = "Please choose a folder from the list"
MsgBox Msg, vbCritical, MsgText
DoCmd.GoToControl "folderlist"
Exit Sub
End If
username() = Split(Me.userlist, ",")
MsgBox Join(username())
Set db = DBEngine(0)(0)
Set RS = db.OpenRecordset("tblPra", DB_OPEN_DYNASET)
RS.FindFirst "[praNo] = """ & username() & """"
varx() = DLookup("praID", "tblPra", "[praNo] = 'username()'")
Set RS = db.OpenRecordset("tblFolder", DB_OPEN_DYNASET)
RS.FindFirst "[folder] = """ & Me.folderlist & """"
vary = DLookup("folderID", "tblFolder", "[folder] = " & "forms!frmrelationship!folderlist")
Response = MsgBox("You are about to create a relationship. Continue?", vbYesNo)
If Response = vbNo Then
Exit Sub
Else
cmdAddRecord varx(), vary
End If
End Sub
Private Sub cmdAddRecord(x(), y)
Dim stDocName As String, db As Database, RS As Recordset, FindPraNumber As String
Dim exists As Boolean
Dim total As Integer
Set db = DBEngine(0)(0)
Set RS = db.OpenRecordset("tblRelationship", DB_OPEN_DYNASET)
exists = False
If Not RS.EOF Then RS.MoveLast
total = RS.RecordCount
'check to see if relationship exists already
RS.FindFirst "[praID] = " & x() & ""
If RS.NoMatch Then
exists = False
Else
If RS("folderID") = y Then
exists = True
Else
For i = 1 To total Or exists = True
RS.FindNext "[praID] = " & x & ""
If RS.NoMatch Then
Else
If RS("folderID") = y Then exists = True
End If
Next i
End If
End If
If exists = False Then
RS.addNew
RS("praID").Value = x
RS("folderID").Value = y
RS.Update
Msg = "Relationship has now been created"
MsgBox Msg, vbInformation, MsgText
Else
Msg = "Relationship already exists"
MsgBox Msg, vbCritical, MsgText
End If
End Sub
You can't do this:
varx() = DLookup("praID", "tblPra", "[praNo] = 'username()'")
You can't assign an array using DLookup, DLookup can't pull an array of IDs, username() should be username(n), and the concatenating of username is wrong. In fact, the only valid parts in this sentence are "tblPra" and "[praNo] = ".
So rethink your concept. There is no reason to complicate matters when straight recordsets or a query can do the job.

Open a workbook using FileDialog and manipulate it

I found this code here on StackOverflow:
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file to kill his non colored cells"
.Filters.Add "Excel", "*.xls"
.Filters.Add "All", "*.*"
If .Show = True Then
txtFileName = .SelectedItems(1)
End If
End With
I know this code should select a file in FileDialog.
However, once I have chosen the .xls file, how do I manipulate the file? In other words, where is my file object for me to manipulate?
I would like someone to continue this code to make some simple manipulation on the workbook so I could learn how to do those simple things on a workbook that I opened.
There are two approaches for you (I prefer using first one). In both approaches wb variable stores opened workbook. I commented code in details, but if you have some questions - ask:)
First approach:
Sub test1()
Dim xlFileName
Dim wb As Workbook
xlFileName = GetOpenFilename("Excel (*.xls*),*.xls*", 1, _
"Please select the file to kill his non colored cells")
'if user pressed CANCEL - exit sub
If xlFileName = False Then
MsgBox "User pressed CANCEL"
Exit Sub
End If
'Tries to open workbook with choosen file name
On Error Resume Next
Set wb = Application.Workbooks.Open(xlFileName)
On Error GoTo 0
'If we can't find workbook with choosen path, exit Sub
If wb Is Nothing Then
MsgBox "Can't find file"
Exit Sub
End If
'your code here
wb.Worksheets("Sheet1").Range("A1").Value = "test"
'close workbook with saving changes
wb.Close SaveChanges:=True
Set wb = Nothing
End Sub
Second approach:
Sub test()
Dim xlFileName As String
Dim fd As Office.FileDialog
Dim wb As Workbook
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file to kill his non colored cells"
.Filters.Add "Excel", "*.xls*"
.Filters.Add "All", "*.*"
If .Show Then
xlFileName = .SelectedItems(1)
Else
'if user pressed CANCEL - exit sub
MsgBox "User pressed CANCEL"
Exit Sub
End If
End With
'Tries to open workbook with choosen file name
On Error Resume Next
Set wb = Workbooks.Open(xlFileName)
On Error GoTo 0
'If we can't find workbook with choosen path, exit Sub
If wb Is Nothing Then
MsgBox "Can't find file"
Exit Sub
End If
'your code here
wb.Worksheets("Sheet1").Range("A1").Value = "test"
'close workbook with saving changes
wb.Close SaveChanges:=True
Set wb = Nothing
End Sub
Here's an example:
Dim wb As Workbook
Dim ws As Worksheet
Dim r As Range
Set wb = Workbooks.Open(txtfilename) ' the file path you selected in FileDialog
Set ws = wb.Worksheets(1)
Set r = ws.Cells(1, 1)
With r
.Value = "Hello world!"
.Interior.Color = RGB(255,20,20) 'bright red
End With

Resources