MS-ACCESS Copying file via vba with file dialog - vba

I'm trying to create a button that opens up a file dialog, then lets you select a image to copy into a folder with the database. I've been working with this code but I'm stuck at the filecopy command, I can't seem to format it correctly. I use the pathway of the database plus a few folders then finally a combo box to select the specific folder to create the pathway (so that it doesn't break if the database is moved, and the combo box sorts the images based on category). Here's the code I've been using. Thanks guys.
Private Sub Command156_Click()
Dim fDialog As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim varFile As Variant
' Set up the File Dialog. '
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
fd.InitialFileName = [Application].[CurrentProject].[Path]
With fDialog
' Allow user to make multiple selections in dialog box '
.AllowMultiSelect = False
' Set the title of the dialog box. '
.Title = "Please select a Image"
' Clear out the current filters, and add our own.'
.Filters.Clear
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the '
' user picked at least one file. If the .Show method returns '
' False, the user clicked Cancel. '
If .Show = True Then
filecopy([.SelectedItems],[GetDBPath] & "\Images\Equipment\" & Combo153)
Else
End If
End With
End Sub

Using Siddharth routs suggestion, I removed the extra brackets and made a few tweaks and voila! the code worked. I tried engineersmnky method but the pathway wasn't generating correctly. To fix the code itself, the only real error was that on the destination part of the file copy, there was no file name, So I used
Dir(Trim(.SelectedItems.Item(1)
To get the file name and tacked it on the end. Heres the rest of the code for anyone else who wants it.
Private Sub Command156_Click()
Dim fDialog As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim varFile As Variant
' Set up the File Dialog. '
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
fd.InitialFileName = Application.CurrentProject.Path
With fDialog
' Allow user to make multiple selections in dialog box '
.AllowMultiSelect = False
' Set the title of the dialog box. '
.Title = "Please select a Image"
' Clear out the current filters, and add our own.'
.Filters.Clear
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the '
' user picked at least one file. If the .Show method returns '
' False, the user clicked Cancel. '
If .Show = True Then
' This section takes the selected image and copy's it to the generated path'
' the string takes the file location, navigates to the image folder, uses the combo box selection to decide the file category, then uses the name from the filedialog to finish the path'
FileCopy .SelectedItems(1), Application.CurrentProject.Path & "\Images\Equipment\" & Combo153 & "\" & Dir(Trim(.SelectedItems.Item(1)))
Else
End If
End With
End Sub

I have answered this question here but I'll repost for you
Here is a concept
Sub Locate_File()
Dim fDialog As Office.FileDialog
Dim file_path As String
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
'Set the title of the dialog box.
.Title = "Please select one or more files"
'Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "All Files", "*.*"
'Show the dialog box. If the .Show method returns True, the
'user picked at least one file. If the .Show method returns
'False, the user clicked Cancel.
If .Show = True Then
file_path = .SelectedItems(1)
Copy_file file_path,Combo153
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End
Sub Copy_file(old_path As String, file_name As String)
Dim fs As Object
Dim images_path As String
images_path = CurrentProject.Path & "\Images\Equipment\"
Set fs = CreateObject("Scripting.FileSystemObject")
fs.CopyFile old_path, images_path & file_name
Set fs = Nothing
End
You may need to make changes and you must require the Microsoft Office 12.0 Object Library for FileDialog to work. Much of the FileDialog code was taken from Microsoft.

Related

VBA Excel FileDialog to set/reset filters

I have a macro that asks a user to choose multiple files for data analysis. User selects a Excel or CSV file first (XLSX, XLS, CSV), then asks for a second file but CSV only. The intent of the tool is to combine the two data files into one.
In one Sub, I ask the user to select any compatible XLSX, XLS, or CSV files using the FileDialog code:
Dim myObj As Object
Dim myDirString As String
Set myObj = Application.FileDialog(msoFileDialogFilePicker)
With myObj
.InitialFileName = "C:\Users\" & Environ$("Username") & "\Desktop"
.Filters.Add "Custom Excel Files", "*.xlsx, *.csv, *.xls"
.FilterIndex = 1
If .Show = False Then MsgBox "Please select Excel file.", vbExclamation: Exit Sub
myDirString = .SelectedItems(1)
End With
It seems to filter appropriately:
After this data analysis in complete, then the user runs a second sub to select another file, but it must be a CSV file only. So I use this code to request CSV:
Dim yourObj3 As Object
Dim yourDirString3 As String
Set yourObj3 = Application.FileDialog(msoFileDialogFilePicker)
With yourObj3
.InitialFileName = "C:\Users\" & Environ$("Username") & "\Desktop"
.Filters.Add "CSV Files", "*.csv"
.FilterIndex = 1
If .Show = False Then MsgBox "Please select CSV file.", vbExclamation: Exit Sub
yourDirString3 = .SelectedItems(1)
End With
The problem is the FileDialog box remembers the first filter (Custom XLS) and they need to click the drop down to see the appropriate filter for CSV only...
So this would certainly be confusing to the user...I'm guessing I need to "clear" our that first filter after the user completes the first macro. Any suggestions on that code to clear (or reset) the first filter?
Tried adding this below it when I found what I thought was a similar question FileDialog persists previous filters:
With .Filters
.Clear
End With
But results in Compile error: Invalid or unqualified reference
This works in my environment. The only thing I made differently was to declare dialogs as FileDialog instead of Object.
Sub Test()
Dim myObj As FileDialog
Dim myDirString As String
Set myObj = Application.FileDialog(msoFileDialogFilePicker)
With myObj
.InitialFileName = "C:\Users\" & Environ$("Username") & "\Desktop"
.Filters.Clear
.Filters.Add "Custom Excel Files", "*.xlsx, *.csv, *.xls"
.FilterIndex = 1
.Show
End With
Dim yourObj3 As FileDialog
Dim yourDirString3 As String
Set yourObj3 = Application.FileDialog(msoFileDialogFilePicker)
With yourObj3
.InitialFileName = "C:\Users\" & Environ$("Username") & "\Desktop"
.Filters.Clear
.Filters.Add "CSV Files", "*.csv"
.FilterIndex = 1
.Show
End With
End Sub
Although it is not directly the answer to the specific msoFileDialogFilePicker from the OP (and googled this answer), I had the same problem with the msoFileDialogSaveAs dialog in Excel 2010 where errors are raised trying to modify the filters in any way because it obviously is not supported :-/
The msoFileDialogSaveAs dialog does NOT support file filters

End If in Access VBA giving me fits

I keep getting an error in this code saying "End If without Block If". I've looked at it and can't see the problem, printed it out and connected all the If statements to their joining End If, and everything looks right.
Is something else throwing e off, like that With/End With block?
Private Sub cmd__Import_Eligibility_Click()
' Requires reference to Microsoft Office 11.0 Object Library.
Dim fDialog As FileDialog
Dim varFile As Variant
Dim filelen As Integer
Dim filename As String
Dim tblname As String
' Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
fDialog.InitialFileName = "oo*.*"
With fDialog
' Set the title of the dialog box.
.Title = "Please select a file"
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel Spreadsheets", "*.xls*"
.Filters.Add "Comma Separated", "*.CSV"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
'Loop through each file selected and add it to our list box.
varFile = fDialog.SelectedItems(1)
If Right(varFile, 4) = ".xls" Or Right(varFile, 5) = ".xlsx" Then
'get only file name
For a = Len(varFile) To 1 Step -1
If Mid(varFile, 1) = "\" Then
filelen = a
End If
Exit For
filename = Right(varFile, filelen)
tblname = Left(filename, InStr(filename, ".") - 1)
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, tblname, filename, True
End If 'ERRORS OUT ON THIS LINE ==========================
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
As Scott posted as a comment, your For...Next loop construct is malformed:
For a = Len(varFile) To 1 Step -1
If Mid(varFile, 1) = "\" Then
filelen = a
End If
Exit For
There's no such thing as a For...Exit For loop. You mean to do this:
For a = Len(varFile) To 1 Step -1
If Mid(varFile, 1) = "\" Then
filelen = a
Exit For
End If
Next
Otherwise the compiler is seeing [roughly] this:
If [bool-expression] Then
For [for-loop-setup]
If [bool-expression] Then
[instructions]
End If
Exit For
[instructions]
End If '<~ expecting "Next" before that "End If" token.
Running an auto-indenter would have made this problem obvious, I think. I happen to manage an open-source project that ported the popular Smart Indenter VBE add-in to .NET, so that it can run in 64-bit environments. See rubberduckvba.com for all the features.

Open Excel from Word using FileDialog

What I want to do is:
Press a button in my Microsoft Word doc it will prompt me to select a document in the file explorer.
Select my document the relevant fields in my word doc will be populated.
This will be populated based upon information in the document (the month) and using a Match function it will search for the correct row/column in the selected excel document and return the value.
I am stuck on the FileDialog(msoFileDialogFilePicker) section of my code below.
For the purpose of my document I can not enter the direct file path, the file path needs to be taken from the FileDialog function (or something similar).
I have also tried GetOpenFilename. I am unsure how to do this. My code currently opens FileDialog and lets me select a file, but I can not pass the file path onto my colNum1 line.
The error I get is Run-time error '91'. Object variable or With Block variable not set.
I am open to suggestions and any help is much appreciated.
Sub KPI_Button()
'
' KPI_Button Macro
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim strFile As String
Dim Doc As String
Dim Res As Integer
Dim dlgSaveAs As FileDialog
Doc = ThisDocument.Name
Set dlgSaveAs = Application.FileDialog(msoFileDialogFilePicker)
Res = dlgSaveAs.Show
colNum1 = WorksheetFunction.Match("(Month)", ActiveWorkbook.Sheets("Sheet1").Range("A2:I2"), 0)
ThisDocument.hoursworkedMonth.Caption = exWb.Sheets("Sheet1").Cells(3, colNum1)
exWb.Close
Set exWb = Nothing
End Sub
try a dialog that specifies an Excel extension as such:
Sub GetNames()
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Excel files", "*.xls*", 1
If .Show = True Then
If .SelectedItems.Count > 0 Then
'this is the path you need
MsgBox .SelectedItems(1)
Else
MsgBox "no valid selection"
End If
End If
End With
End Sub

How can I add a paragraph between images?

I have been adding a range of buttons to a customUi menu in Word. One of the buttons imports one or more images form a library folder on a server, but I can't get it to put a paragraph return between each image when it adds them to the page.
With fd
.InitialFileName = strFolder & "\*.png; *.jpg; *.gif"
.ButtonName = "Insert"
.AllowMultiSelect = True ' Make multiple selection
.Title = "Choose one or more pictures from the library"
.InitialView = msoFileDialogViewPreview
'Sets the initial file filter to number 2.
' .FilterIndex = 2
'Use the Show method to display the File Picker dialog box and return the user's action.
'If the user presses the action button...
If .Show = -1 Then
'Step through each string in the FileDialogSelectedItems collection.
For Each vrtSelectedItem In .SelectedItems
'vrtSelectedItem is a String that contains the path of each selected item.
Selection.InlineShapes.AddPicture FileName:= _
vrtSelectedItem _
, LinkToFile:=False, SaveWithDocument:=True
Next vrtSelectedItem
I've tried adding a paragraph line [Selection.TypeParagraph] at various places, but it just adds the return after all of the images.
Any help would be appreciated.
did you try to use:
Selection.InsertParagraphAfter
Selection.Move
which is possibly what you are looking for??
Add the line before Next statement.

How to take a browsed text file and put it into a list box VBA

So i'm new to using access/VBA and i'm having trouble getting this to work.
Private Sub Get_File_Click()
Dim fdlg As Office.FileDialog
Dim pipe_file As Variant
Dim FileName As String
Dim file As String
Dim fn As Integer
' Clear contents of listboxes and textboxes. '
Me.OrigFile.RowSource = ""
Me.ConvertFile.RowSource = ""
Me.FileName = ""
' Set up the File dialog box. '
Set fdlg = Application.FileDialog(msoFileDialogFilePicker)
With fdlg
.AllowMultiSelect = False
' Set the title of the dialog box. '
.Title = "Select pipe delimited file"
' Clear out the current filters, and then add your own. '
.Filters.Clear
.Filters.Add "Text Files", "*.txt"
' Show the dialog box. If the .Show method returns True, the '
' user picked a file. If the .Show method returns '
' False, the user clicked Cancel. '
If .Show = True Then
file = fdlg
fn = FreeFile
Open file For Input As #fn
Do While Not EOF(fn)
Line Input #fn, pipe_file
Me.OrigFile.AddItem pipe_file
Loop
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
This is what i have so far. origFile is the listbox i'm trying to put the textfile into.
Any help is appreciated
Thanks
Comments added Inline:
Private Sub Get_File_Click()
Dim fdlg As Office.FileDialog
Dim pipe_file As Variant
'Why two vars named 'FileName' and 'file'? Since they are both string, assuming just one of these will do.
Dim FileName As String
'Dim file As String
Dim fn As Integer
'Need variant variable to get file name
Dim varFile As Variant
Me.OrigFile.RowSource = ""
Me.ConvertFile.RowSource = ""
'Don't use ME here. Unless you have an object named FileName (which I'm not sure why you would in this case)
'Me.FileName = ""
FileName = ""
Set fdlg = Application.FileDialog(msoFileDialogFilePicker)
With fdlg
.AllowMultiSelect = False
.Title = "Select pipe delimited file"
.Filters.Clear
.Filters.Add "Text Files", "*.txt"
If .Show = True Then
'Never used this code before but this is how you get the file name:
'Seems lame to have three lines of code to get one file name, but I guess this is the way this control works
For Each varFile In .SelectedItems
FileName = varFile
Next varFile
'The invalid code below was causing the error and it is no longer necessary.
'However, also wanted to point out that you are already in a With block for fldg so the fdlg object is not required
'FileName = fdlg.SelectedItems
fn = FreeFile 'FreeFile = Good!
'Commented out the line below because file is not used
'Open file For Input As #fn
Open FileName For Input As #fn
Do While Not EOF(fn)
Line Input #fn, pipe_file
Me.OrigFile.AddItem pipe_file
Loop
'Make sure to close the file too!
Close #fn
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
Also, one final tip, make sure you have the following line of code declared at the top of your modules:
Option Explicit
This will prevent you from accidentally typing in the name of a variable incorrectly.
You can have the VBA project add this line by default if you click "Tools/Options" and then select "Require Variable Declaration" in the Editor tab.
I think your problem is the line
file = fdlg
should be
file = fdlg.SelectedItems(1)