Select a file to import then process

ECEK

Registered User.
Local time
Today, 22:42
Joined
Dec 19, 2012
Messages
717
I've always struggled with this but never pursued it.

1.I want my user to press the cmdbutton.
The window directs to a specific folder on my computer.

2.The user selects the csv file (could be named anything - usually date orientated eg Income 2018.csv)

3. The file is uploaded the window closes and then a series of checks and queries ensues.

I have always had to rename the file to a specific name and use the import spec.

Also I struggle to continue the process after selecting the file.

Could you point me in the right direction please you lovely people ?
 
Last edited:
usage:
vFile = UserPick1File("c:\folder")
if vFile <> "" then docmd.TransferSpreadsheet acImport ,acSpreadsheetTypeExcel12, "tTable", vFile, true


Code:
Public Function UserPick1File(pvPath)
Dim strTable As String
Dim strFilePath As String
Dim sDialog As String, sDecr  As String, sExt As String

If IsMissing(pvPath) Then pvPath = "c:\"

With Application.FileDialog(msoFileDialogFilePicker)   'MUST ADD REFERENCE : Microsoft Office 11.0 Object Library
    .AllowMultiSelect = False
    .Title = "Locate a file to Import"
    .ButtonName = "Import"
    .Filters.Clear

    '.Filters.Add "Excel Files", "*.xlsx"
    .Filters.Add "Text Files", "*.csv"
    .Filters.Add "All Files", "*.*"
    .InitialFileName = pvPath
    .InitialView = msoFileDialogViewList    'msoFileDialogViewThumbnail

        If .show = 0 Then
           'There is a problem
           Exit Function
        End If

    'Save the first file selected
    UserPick1File = Trim(.SelectedItems(1))
End With
End Function
 
Hi Ranman
Thanks for you time. I have placed the Function into a Module but I am unsure what the "usage: vfile etc " is?

Could you help further? I'm afraid my VBA is somewhat basic.

I have Microsoft Office 15 Object Library installed as a reference.
 
What he is trying to instruct you to do is
1) DIM a string with a name that makes sense in context for your application.
2) Use the function he created to return a file name to the string variable you created in 1 above.
3) CHECK to see if your user has selected a file. IF they have, then you use DoCmd to import your selected file based on the specification you are already using.

For help with how you use DoCmd.TransferSpreadSheet please look HERE for the full syntax.

Does this explain what he is recommending better?
 
The 2 vFile lines would be code in another procedure, perhaps a button Click event.
 
Thanks Guys
I was being dumb and figured it out.
However my imports are csv files not a spreadsheet.

I have saved an importspecification

Could you help with the correct way to import a csv.

I've tried to follow the website and got this far but it pulls an error.

DoCmd.TransferText (acImportDelim,AllocatedCashImportspecification,tblAllocatedCashImport,,1,,)
 
I'd look at the help and example here

DoCmd.TransferText acImportDelim, AllocatedCashImportspecification, tblAllocatedCashImport, <FILE TO IMPORT HERE>, 1

You have too many parameters, you don't need the trailing colons, and you don't seem to be telling it what file you want to import. The '1' is in the spot for "I have field names as headers for my import file". If this is true, great. If not, well, you'll skip the first record.
 
Hi Mark
Thanks for your response. The issue with <FILE TO IMPORT HERE> is that the file name will change. (See original point 2)

what I need is:
DoCmd.TransferText acImportDelim, AllocatedCashImportspecification, tblAllocatedCashImport, <FILE THAT IVE JUST SELECTED >, 1
 
Hi Mark
Thanks for your response. The issue with <FILE TO IMPORT HERE> is that the file name will change. (See original point 2)

what I need is:
DoCmd.TransferText acImportDelim, AllocatedCashImportspecification, tblAllocatedCashImport, <FILE THAT IVE JUST SELECTED >, 1

Try this code instead , it opens a normal dialogue box to let the user select the file. It then passes the entire path and filename to your variable.
There are other functions of use but you will use the variable

myFilePath = GetOpenFile()

modSaveASDialogue
Code:
Option Compare Database
Option Explicit

' This code was originally written by Ken Getz.
' It is not to be altered or distributed, 'except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
' Code originally courtesy of:
' Microsoft Access 95 How-To
' Ken Getz and Paul Litwin
' Waite Group Press, 1996
' Revised to support multiple files:
' 28 December 2007

Type tagOPENFILENAME
    lStructSize As Long
    hwndOwner As Long
    hInstance As Long
    strFilter As String
    strCustomFilter As String
    nMaxCustFilter As Long
    nFilterIndex As Long
    strFile As String
    nMaxFile As Long
    strFileTitle As String
    nMaxFileTitle As Long
    strInitialDir As String
    strTitle As String
    flags As Long
    nFileOffset As Integer
    nFileExtension As Integer
    strDefExt As String
    lCustData As Long
    lpfnHook As Long
    lpTemplateName As String
End Type

Declare Function aht_apiGetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" (OFN As tagOPENFILENAME) As Boolean
Declare Function aht_apiGetSaveFileName Lib "comdlg32.dll" Alias "GetSaveFileNameA" (OFN As tagOPENFILENAME) As Boolean
Declare Function CommDlgExtendedError Lib "comdlg32.dll" () As Long

Global Const ahtOFN_READONLY = &H1
Global Const ahtOFN_OVERWRITEPROMPT = &H2
Global Const ahtOFN_HIDEREADONLY = &H4
Global Const ahtOFN_NOCHANGEDIR = &H8
Global Const ahtOFN_SHOWHELP = &H10
Global Const ahtOFN_NOVALIDATE = &H100
Global Const ahtOFN_ALLOWMULTISELECT = &H200
Global Const ahtOFN_EXTENSIONDIFFERENT = &H40
Global Const ahtOFN_PATHMUSTEXIST = &H800
Global Const ahtOFN_FILEMUSTEXIST = &H1000
Global Const ahtOFN_CREATEPROMPT = &H2000
Global Const ahtOFN_SHAREAWARE = &H4000
Global Const ahtOFN_NOREADONLYRETURN = &H8000
Global Const ahtOFN_NOTESTFILECREATE = &H10000
Global Const ahtOFN_NONETWORKBUTTON = &H20000
Global Const ahtOFN_NOLONGNAMES = &H40000

'New for Windows 95
Global Const ahtOFN_EXPLORER = &H80000
Global Const ahtOFN_NODEREFERENCELINKS = &H100000
Global Const ahtOFN_LONGNAMES = &H200000



Function GetSaveAsLocFromUser() As String
    Dim strFilter As String
    Dim lngflags As Long
    strFilter = ahtAddFilterItem(strFilter, "Excel Files (*.xls, *.xlsl)", "*.xls;*.xlsl")

    Dim result As Variant
    'result = ahtCommonFileOpenSave(InitialDir:="C:\", Filter:=strFilter, FilterIndex:=3, Flags:=lngFlags, DialogTitle:="Hello! Open Me!")
    result = ahtCommonFileOpenSave(InitialDir:="C:\", flags:=lngflags, DialogTitle:="Hello! Open Me!")
    
    If lngflags And ahtOFN_ALLOWMULTISELECT Then

        If IsArray(result) Then
            Dim i As Integer

            For i = 0 To UBound(result)
                MsgBox result(i)
            Next i

        Else
            MsgBox result
            GetSaveAsLocFromUser = result
        End If

    Else
        MsgBox result
        GetSaveAsLocFromUser = result
    End If

    ' Since you passed in a variable for lngFlags,
    ' the function places the output flags value in the variable.

    Debug.Print Hex(lngflags)

End Function


Function GetOpenFile(Optional varDirectory As Variant, Optional varTitleForDialog As Variant, Optional varOrigFilter As String) As Variant
    ' Here's an example that gets an Access database name.
    Dim strFilter As String
    Dim lngflags As Long
    Dim varFileName As Variant

    ' Specify that the chosen file must already exist,
    ' don't change directories when you're done
    ' Also, don't bother displaying
    ' the read-only box. It'll only confuse people.

    lngflags = ahtOFN_FILEMUSTEXIST Or ahtOFN_HIDEREADONLY Or ahtOFN_NOCHANGEDIR

    If IsMissing(varDirectory) Then
        varDirectory = ""
    End If

    If IsMissing(varTitleForDialog) Then
        varTitleForDialog = ""
    End If

    ' Define the filter string and allocate space in the "c"
    ' string Duplicate this line with changes as necessary for
    ' more file templates.
    
    strFilter = ahtAddFilterItem(strFilter, varOrigFilter)

    ' Now actually call to get the file name.
    varFileName = ahtCommonFileOpenSave(OpenFile:=True, InitialDir:=varDirectory, filter:=strFilter, _
    flags:=lngflags, DialogTitle:=varTitleForDialog)

    If Not IsNull(varFileName) Then
        varFileName = TrimNull(varFileName)
    End If

    GetOpenFile = varFileName

End Function

Function ahtCommonFileOpenSave(Optional ByRef flags As Variant, Optional ByVal InitialDir As Variant, _
Optional ByVal filter As Variant, Optional ByVal FilterIndex As Variant, Optional ByVal DefaultExt As Variant, _
Optional ByVal fileName As Variant, Optional ByVal DialogTitle As Variant, Optional ByVal hwnd As Variant, _
Optional ByVal OpenFile As Variant) As Variant
    ' This is the entry point you'll use to call the common
    ' file open/save dialog. The parameters are listed
    ' below, and all are optional.
    ' In:
    ' Flags: one or more of the ahtOFN_* constants, OR'd together.
    ' InitialDir: the directory in which to first look
    ' Filter: a set of file filters, set up by calling
    ' AddFilterItem. See examples.
    ' FilterIndex: 1-based integer indicating which filter
    ' set to use, by default (1 if unspecified)
    ' DefaultExt: Extension to use if the user doesn't enter one.
    ' Only useful on file saves.
    ' FileName: Default value for the file name text box.
    ' DialogTitle: Title for the dialog.
    ' hWnd: parent window handle
    ' OpenFile: Boolean(True=Open File/False=Save As)
    ' Out:
    ' Return Value: Either Null or the selected filename

    Dim OFN As tagOPENFILENAME
    Dim strFileName As String
    Dim strFileTitle As String
    Dim fResult As Boolean
    ' Give the dialog a caption title.
    If IsMissing(InitialDir) Then InitialDir = CurDir
    If IsMissing(filter) Then filter = ""
    If IsMissing(FilterIndex) Then FilterIndex = 1
    If IsMissing(flags) Then flags = 0&
    If IsMissing(DefaultExt) Then DefaultExt = ""
    If IsMissing(fileName) Then fileName = ""
    If IsMissing(DialogTitle) Then DialogTitle = ""
    If IsMissing(hwnd) Then hwnd = Application.hWndAccessApp
    If IsMissing(OpenFile) Then OpenFile = False
    ' Allocate string space for the returned strings.
    strFileName = Left(fileName & String(256, 0), 256)
    strFileTitle = String(256, 0)
    ' Set up the data structure before you call the function
    
    With OFN
        .lStructSize = Len(OFN)
        .hwndOwner = hwnd
        .strFilter = filter
        .nFilterIndex = FilterIndex
        .strFile = strFileName
        .nMaxFile = Len(strFileName)
        .strFileTitle = strFileTitle
        .nMaxFileTitle = Len(strFileTitle)
        .strTitle = DialogTitle
        .flags = flags
        .strDefExt = DefaultExt
        .strInitialDir = InitialDir
        ' Didn't think most people would want to deal with
        ' these options.
        .hInstance = 0
        '.strCustomFilter = ""
        '.nMaxCustFilter = 0
        .lpfnHook = 0
        'New for NT 4.0
        .strCustomFilter = String(255, 0)
        .nMaxCustFilter = 255
    End With
    
    ' This will pass the desired data structure to the
    ' Windows API, which will in turn it uses to display
    ' the Open/Save As Dialog.
    
    If OpenFile Then
        fResult = aht_apiGetOpenFileName(OFN)
    Else
        fResult = aht_apiGetSaveFileName(OFN)
    End If

    ' The function call filled in the strFileTitle member
    ' of the structure. You'll have to write special code
    ' to retrieve that if you're interested.
    
    If fResult Then
        ' You might care to check the Flags member of the
        ' structure to get information about the chosen file.
        ' In this example, if you bothered to pass in a
        ' value for Flags, we'll fill it in with the outgoing
        ' Flags value.
        
        If Not IsMissing(flags) Then flags = OFN.flags
        If flags And ahtOFN_ALLOWMULTISELECT Then
            ' Return the full array.
            Dim Items As Variant
            Dim Value As String
            Value = OFN.strFile
            ' Get rid of empty items:
            Dim i As Integer
            For i = Len(Value) To 1 Step -1
            
              If Mid$(Value, i, 1) <> Chr$(0) Then
                Exit For
              End If

            Next i
            
            Value = Mid(Value, 1, i)
            ' Break the list up at null characters:
            Items = Split(Value, Chr(0))
            ' Loop through the items in the "array",
            ' and build full file names:
            Dim numItems As Integer
            Dim result() As String
            numItems = UBound(Items) + 1

            If numItems > 1 Then
                ReDim result(0 To numItems - 2)
                
                For i = 1 To numItems - 1
                    result(i - 1) = FixPath(Items(0)) & Items(i)
                Next i

                ahtCommonFileOpenSave = result
            Else
                ' If you only select a single item,
                ' Windows just places it in item 0.
                ahtCommonFileOpenSave = Items(0)
            End If

        Else
            ahtCommonFileOpenSave = TrimNull(OFN.strFile)
        End If

    Else
        ahtCommonFileOpenSave = vbNullString
    End If

End Function

Function ahtAddFilterItem(strFilter As String, strDescription As String, Optional varItem As Variant) As String
    ' Tack a new chunk onto the file filter.
    ' That is, take the old value, stick onto it the description,
    ' (like "Databases"), a null character, the skeleton
    ' (like "*.mdb;*.mda") and a final null character.
    
    If IsMissing(varItem) Then varItem = "*.*"
    ahtAddFilterItem = strFilter & strDescription & vbNullChar & _
    varItem & vbNullChar

End Function

Private Function TrimNull(ByVal strItem As String) As String
    Dim intPos As Integer

    intPos = InStr(strItem, vbNullChar)

    If intPos > 0 Then
        TrimNull = Left(strItem, intPos - 1)
    Else
        TrimNull = strItem
    End If

End Function

Private Function FixPath(ByVal path As String) As String

    If Right$(path, 1) <> "\" Then
        FixPath = path & "\"
    Else
        FixPath = path
    End If

End Function
 

Users who are viewing this thread

Back
Top Bottom