How can I add a paragraph between images? - vba

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.

Related

Is there a method to use VBA to insert multiple images and insert them in order of selection through the dialog box?

I'm creating multiple reports with a ton of images (50+ images). I need to insert them in a specific order. I have a running script which opens a Dialog box and I can select the photos that I want, but when I press OK, it inserts the images in alphabetical order. I want them to be inserted in the order I select them from the dialog box.
I've tried to find methods relating to insertion methods in VBA. Nothing?
Sub InsertSelectedPixs()
Dim fd As FileDialog
Dim picPath As String
Dim fnd As Variant
Dim rep As Variant
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant
With fd
.InitialFileName = "*"
.AllowMultiSelect = True
.Filters.Clear
.Filters.Add "Images", "*.png; *.jpg; *.jpeg; *.tif"
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
Set MyPic = ActiveDocument.InlineShapes.AddPicture(vrtSelectedItem)
picName = Right(vrtSelectedItem, Len(vrtSelectedItem) - InStrRev(vrtSelectedItem, "\"))
MyPic.Select
MyPic.LockAspectRatio = msoTrue
MyPic.Width = CentimetersToPoints(7.25)
Selection.MoveDown wdLine
Selection.TypeText Chr(11)
Selection.InsertCaption Label:="Figure", Title:=". " & picName, Position:=wdCaptionPositionBelow
Selection.Collapse wdCollapseEnd
Selection.TypeText Chr(10)
Next vrtSelectedItem
Else
End If
End With
Set fd = Nothing
With ActiveDocument.Content.Find
.Execute FindText:=".jpg", ReplaceWith:="", Format:=True, Replace:=wdReplaceAll
End With
ActiveDocument.Range(0, 0).Select
Selection.WholeStory
Dim oRange As Word.Range
If ActiveDocument.Range.Tables.Count <> 0 Then Exit Sub
Set oRange = ActiveDocument.Range
oRange.ConvertToTable Separator:=wdSeparateByParagraphs, Format:=wdTableFormatGrid1, NumColumns:=2
Set oRange = Nothing
End Sub
The images get imported into the Word doc in alphabetical order rather than the selected order during the selection screen (file dialog box)
The issue here is that the FileDialog file picker is always going to return a collection of selected items that are sorted in the order that they appeared in the FileDialog (e.g., alphabetical by file name). It does not have a method to preserve the specific actions the user took to get to the final list of selections.
In order to solve this, you would need to build your own combo box function that added items to a collection each time the user selected one from the list. This would preserve the order of the user's choices and would enable you to do what you are looking for.

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.

Copy the contents of a document(s) through FileDialogbox picker, to a new one

With MS_Word 2010 I have been trying to achieve the way to copy the contents(whole) of one file to a new one retrieving the file name of the original and adding it to the new one with the suffix "Copy".
All this process has a reason, since the Original document has only a few editable section and have protection enable (And I cant disable it) but I need to review it with other macro, so with a Copy of the contents in a new document I have been able to apply my whole macro. I also know of the method CopyFile but since this method copy also the characteristic of the original doc (the constrains in edit) I decide not to use it.
Searching around and using the recorder(for the copy actions) i have been able to come with this:
Sub Backup()
Dim DocName As String
Dim DocPath As String
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Declare a variable to contain the path of each selected item. Even though the path is aString, the variable must be a Variant because For Each...Next, routines only work with Variants and Objects.
Dim vrtSelectedItem As Variant
'Use a With...End With block to reference the FileDialog object.
With fd
'Allow the user to select multiple files.
.AllowMultiSelect = True
'Use the Show method to display the File Picker dialog box and return the user's action.
'If the user presses the button...
If .Show = -1 Then
'Step through each string in the FileDialogSelectedItems collection.
For Each vrtSelectedItem In .SelectedItems
On Error Resume Next
'vrtSelectedItem is aString that contains the path of each selected item. You can use any file I/O functions that you want to work with this path.
'MsgBox "Selected item's path: " & vrtSelectedItem
'Retrieve the name of the current doc (later I found out about .Name, .Path, .FullName ...)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
DocName = fso.GetBaseName(vrtSelectedItem)
'MsgBox "Selected item's : " & DocName
'Retrieve the path without the filename/extention
Documents.Open(vrtSelectedItem).Active
DocPath = ActiveDocument.Path
'MsgBox "Selected item's path: " & DocPath
'Copy the content of the current document
'With Documents(DocName)
With ActiveDocument
.WholeStory
.Copy
End With
'Create Backup File with ability to modify it, since the original is protected by password and only few segments are enable to edit
Documents.Add Template:=DocName & "Copy", NewTemplate:=False, DocumentType:=0
'Since Document.Add its suppose to promp as the Active document
'Paste the contents and save
'With Documents(DocName & "Copy")
With ActiveDocument
.PasteAndFormat (wdUseDestinationStylesRecovery)
.SaveAs DocPath
End With
'Documents(DocName & "Copy").Close SaveChanges:=True
Next
'If the user presses Cancel...
Else
End If
End With
'Set the object variable to Nothing.
Set fd = Nothing
End Sub
But as you guess, it doesn't work as desire and don't create the copy neither the new document with the name. So any scope in the right direction will be appreciate.
Thanks in advance for all the answers.
For future reference here is the code improved, based in the Response of #Charlie
Sub Backup()
Dim DocName As String
Dim NewDoc As Document
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Declare a variable to contain the path of each selected item. Even though the path is aString, the variable must be a Variant because For Each...Next, routines only work with Variants and Objects.
Dim vrtSelectedItem As Variant
'Use a With...End With block to reference the FileDialog object.
With fd
'Allow the user to select multiple files.
.AllowMultiSelect = True
'Use the Show method to display the File Picker dialog box and return the user's action.
'If the user presses the button...
If .Show = -1 Then
'Step through each string in the FileDialogSelectedItems collection.
For Each vrtSelectedItem In .SelectedItems
On Error Resume Next
'vrtSelectedItem is aString that contains the path of each selected item. You can use any file I/O functions that you want to work with this path.
'MsgBox "Selected item's path: " & vrtSelectedItem
'Retrieve the name of the current doc (later I found out about .Name, .Path, .FullName ...)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
DocName = fso.GetBaseName(vrtSelectedItem)
'MsgBox "Selected item's : " & DocName
'Create Backup File with ability to modify it, since the original is protected by password and only few segments are enable to edit
Set NewDoc = Documents.Add
'Since Document.Add its suppose to promp as the Active document
'Paste the contents and save
With NewDoc
Selection.InsertFile FileName:=vrtSelectedItem, Range:=vbNullString, _
ConfirmConversions:=False, Link:=False, Attachment:=False
.SaveAs FileName:=vrtSelectedItem & "_BACKUP.docx"
.Close
End With
Next
'If the user presses Cancel...
Else
End If
End With
'Set the object variable to Nothing.
Set fd = Nothing
End Sub
I would try creating a new Word doc then using this line to "insert the text from the protected Word doc." It's the same as going to the Insert Ribbon tab -> Object -> Text from File.
Selection.InsertFile FileName:="protected.docx", Range:="", _
ConfirmConversions:=False, Link:=False, Attachment:=False

MS-ACCESS Copying file via vba with file dialog

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.