VBA Opening a file with a given destination - excel

I have a function in a macro that allows me to select a file using inputbox, or is it possible to always start showing files at the same time, so that I don't have to look in folders. For example, when the selectFile window appears, the folder should be \banksl\dfs\BH\BPR\
strPath1 = selectFile
If strPath1 = "" Then Exit Function
Set bilans = Workbooks.Open(strPath1, False, True)
Private Function selectFile1()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.InitialFileName = ActiveWorkbook.path
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Excel", "*.xlsm"
If .Show = True Then selectFile = .SelectedItems(1)
End With

Related

Fill textbox with selected items in filemanager

I would like to write a program in VBA.
I would like a window to pop up when the program starts, where I can bring up the file manager with a button and the elements what are (multiple)selected here, would be placed in a textbox under each other and excel would open them all at once.
Now I finished the useform with one button and one textbox, and have a code for the button, to open the file manager and enabled the multiselect. Whats next? Anybody can help me?
Private Sub CommandButton1_Click()
Dim fldlg As FileDialog
Set fldlg = Application.FileDialog(msoFileDialogOpen)
With fldlg
.AllowMultiSelect = True
.Title = "Find"
.InitialFileName = "C:\"
.Filters.Clear
.Filters.Add "Excel", "*.xls,*.xlsx"
End With
rv = fldlg.Show
If rv Then
MsgBox fldlg.SelectedItems(1)
End If
End Sub
To open all the files (or build a string listing them all), you need to cycle through the SelectedItems collection and use each in turn:
Dim fldlg As FileDialog
Set fldlg = Application.FileDialog(msoFileDialogOpen)
Dim strItems
With fldlg
.AllowMultiSelect = True
.Title = "Find"
.InitialFileName = "C:\"
.Filters.Clear
.Filters.Add "Excel", "*.xls,*.xlsx"
rv = .Show
If rv Then
'create a string of text for output using MsgBox
For Each SelectedItem In .SelectedItems
strItems = strItems & SelectedItem & Chr(13)
Next
'display string
MsgBox strItems
'open the files
For Each SelectedItem In .SelectedItems
Workbooks.Open SelectedItem
Next
End If
End With

importing 2 text files at once

I want to import 2 txt files at once to excel through vba. Currently, I can only import 1 txt file.
I want the users to be able the ability to just choose 2 files to be imported.
Sub ImportFiles()
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
Dim path As String
Dim filename As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant
With fd
'Set the initial path to the C:\ drive.
.InitialFileName = ActiveWorkbook.path
'Add a filter that includes the list.
.Filters.Clear
.Filters.Add "Text Files", "*.txt", 1
'The user pressed the button.
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
path = Left(vrtSelectedItem, InStrRev(vrtSelectedItem, "\"))
filename = Right(vrtSelectedItem, Len(vrtSelectedItem) - InStrRev(vrtSelectedItem, "\"))
Call Importfile(path, filename)
Next vrtSelectedItem
Else
End If
End With
Set fd = Nothing
End Sub
Sub Importfile(path As String, filename As String)
Sheets.Add(After:=Sheets("Sheet1")).Name = "Data"
On Error Resume Next
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & path & filename, Destination:=Range("$A$1"))
.Name = filename
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = False
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = xlWindows
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileOtherDelimiter = vbTab
.TextFileDecimalSeparator = "."
.TextFileThousandsSeparator = " "
.Refresh BackgroundQuery:=False
End With
End Sub
I understand that I need to use a loop to loop it to choose 2 files to be imported. But how do i do so?
You need to allow the users to select multiple files, you can do that by adding the AllowMultiSelect option to the file dialog.
Sub ImportFiles()
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
Dim path As String
Dim filename As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant
With fd
.AllowMultiSelect = True
'Set the initial path to the C:\ drive.
.InitialFileName = ActiveWorkbook.path
'Add a filter that includes the list.
.Filters.Clear
.Filters.Add "Text Files", "*.txt", 1
'The user pressed the button.
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
path = Left(vrtSelectedItem, InStrRev(vrtSelectedItem, "\"))
filename = Right(vrtSelectedItem, Len(vrtSelectedItem) - InStrRev(vrtSelectedItem, "\"))
Call Importfile(path, filename)
Next vrtSelectedItem
Else
End If
End With
Set fd = Nothing
End Sub
On the documentation site for VBA you find that.
Sub UseFileDialogOpen()
Dim lngCount As Long
' Open the file dialog
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = True
.Show
' Display paths of each file selected
For lngCount = 1 To .SelectedItems.Count
MsgBox .SelectedItems(lngCount)
Next lngCount
End With
End Sub
So it seems that you just need to add the .count attribute to the .SelectedItems.
Maybe you´ll need to adjust .AllowMultiSelect to true that you can select multiple files at once in the filtedialog.
Sub ImportFiles()
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
Dim path As String
Dim filename As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant
With fd
'Set the initial path to the C:\ drive.
.AllowMultiSelect = True
.InitialFileName = ActiveWorkbook.path
'Add a filter that includes the list.
.Filters.Clear
.Filters.Add "Text Files", "*.txt", 1
'The user pressed the button.
If .Show = -1 Then
For lngCount = 1 To .SelectedItems.Count
path = Left(.SelectedItems(lngCount), InStrRev(.SelectedItems(Count), "\"))
filename = Right(.SelectedItems(Count), Len(.SelectedItems(Count)) - InStrRev(.SelectedItems(Count), "\"))
Call Importfile(path, filename)
Next lngCount
Else
End If
End With
Set fd = Nothing
End Sub

I'm trying to import a `.txt file` into a workbook from another workbook but doesn't work

Let's say i'm working on workbook A and workbook A produce a .txt file.
I also have workbook B witch contain a table that is ready to receive data from a .txt file.
i want to import the .txt fileproduce by workbook A into workbook B and i want to do so with workbook A
here's my code:
Sub result_template()
Dim FL As String
Dim wb As Workbook
Dim restemplate As Object
With Application.FileDialog(msoFileDialogFilePicker) '
.Title = "Select the log file" 'Open the file explorer
.InitialFileName = ThisWorkbook.path & "\" 'for you to select
.InitialView = msoFileDialogViewDetails 'the file you want
.AllowMultiSelect = False 'to format
.Show
If Not .SelectedItems(1) = vbNullString Then Sheets(5).Cells(36, 16).Value = .SelectedItems(1)
End With
With Application.FileDialog(msoFileDialogFilePicker) '
.Title = "Select the result template" 'Open the file explorer
.InitialFileName = ThisWorkbook.path & "\" 'for you to select
.InitialView = msoFileDialogViewDetails 'the file you want
.AllowMultiSelect = False 'to format
.Show
If Not .SelectedItems(1) = vbNullString Then FL = .SelectedItems(1)
Set restemplate = wb.OpenText(FL, 3, xlDelimited, True, True)
'Code to copy the contents of the .txt file to your table
ActiveWorkbook.Close Savechanges:=True filename:="result" & Date
End With
End Sub
I have a syntaxe error on ActiveWorkbook.Close
and have Object variable not set error on Set restemplate = wb.OpenText(FL, 3, xlDelimited, True, True)
what I'm I doing wrong?

Select file and display path

I am trying to show the path of a file I select from a dialog box, in a text box.
Sub SelectMonthlyFile()
Dim Data As Office.FileDialog
Set Data = Application.FileDialog(msoFileDialogFilePicker)
With Data
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
If .Show = True Then
Path = .SelectedItems(1)
End If
End With
End Sub
I show an error at Path = .SelectedItems(1).
variable is not defined
I named my cell Path and assumed that this would get the file path copied and pasted here.
I suggest you rename Data to something more meaningful. I've changed it to just FileDialog. The reason for your error is that the code has no idea what Path is. Note that I omitted the clearing of the filter, it is not needed.
Option Explicit 'always have this
Dim strPath As String 'explicitly declare your variable
Sub SelectMonthlyFile()
Dim FileDialog As Office.FileDialog
Set FileDialog = Application.FileDialog(msoFileDialogFilePicker)
With FileDialog
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
'was anything selected?
If .Show <> 0 Then
strPath = .SelectedItems(1)
Debug.Print strPath
End If
End With
End Sub

Embedding a file into Excel through VBA damages the file

I have the following code
Private Sub btnOpenTemplate_Click()
Dim c As Range
Dim fd As Office.FileDialog, directory As String, fileName As String
Set c = Settings.Range("A1")
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Âûáåðèòå øàáëîí ÏÌÈ."
.Filters.Clear
.Filters.Add "Word 2003", "*.doc?"
If .Show = True Then
fileName = .SelectedItems(1)
End If
End With
If fileName = "" Then
Exit Sub
End If
If Dir(fileName, vbNormal) <> "" Then
If c.Worksheet.OLEObjects.Count > 0 Then
c.Worksheet.OLEObjects(1).Delete
End If
Settings.OLEObjects.Add fileName:=fileName, Link:=False, DisplayAsIcon:=True
End If
Settings.Range("A2").Value = fileName
lblTemplateFile.Caption = fileName
End Sub
Whenever it is executed, the workbook gets damaged and Excel is unable to repair and save it. What could be wrong? What I mean is that the workbook works fine just until I embed an object (Word doc) into it via the macro. Then it gets damaged.

Resources