importing 2 text files at once - excel

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

Related

Loop through files and find and replace columns

I have a VBA script below that loops through files in a folder. I would like to find and replce any "$" with "" (nothing) in columns I and J.
When I run this script it appears to run, but there are no changes within the files. Not too sure where the issue is. Any help would be appreciated.
Thanks!
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Find and replace col I and J
wb.Worksheets(1).Range("I:J").Replace What:="$", Replacement:=""
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
*Edit - I have found it will work with .xlsx files, but not with .csv. I would need it to work with csv, so any suggestions would be great.
Try something like this:
Sub LoopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String, ext
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show = -1 Then myPath = .SelectedItems(1)
End With
If myPath <> "" Then
myPath = myPath & "\"
For Each ext In Array("*.xls*", "*.csv") 'loop different extension patterns
myFile = Dir(myPath & ext)
Do While myFile <> ""
'Debug.Print myFile
Set wb = Workbooks.Open(Filename:=myPath & myFile)
wb.Worksheets(1).Range("I:J").Replace _
What:="$", Replacement:="", LookAt:=xlPart
wb.Close SaveChanges:=True
myFile = Dir()
Loop
Next ext
End If
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Note - where possible you should avoid use of Goto for flow control. You only really need Goto for handling runtime errors (or maybe for breaking out of nested loops).

Excel Macro Saves as PDF

I have a Macro that applies some filters and then exports certain columns as a PDF file, currently the Macro saves the PDF in the same folder as the Excel file but I would like it to ask me where I want to save the file instead, is this possible?
Any help much appreciated! :)
Sub FilterSaveCases()
With ActiveSheet.PageSetup
.LeftHeader = "&B& &20 Doff Stock : " & Format(Now, " ddmmyyyy")
On Error Resume Next
Columns("H:H").AutoFilter.ShowAllData
Columns("H:H").AutoFilter
ActiveSheet.Range("H:H").AutoFilter Field:=1, Criteria1:=">1"
Columns("C:O").EntireColumn.Hidden = True
Columns("P:P").EntireColumn.Hidden = False
ActiveSheet.Pictures("Picture 1").Visible = False
Dim Nm As String
Dim Rng As Range
Set Rng = Range("A1:P198")
Nm = ActiveWorkbook.FullName
Nm = Left(Nm, InStrRev(Nm, ".") - 1) & Format(Now, " ddmmyyyy") & ".pdf"
Rng.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Nm, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=True, OpenAfterPublish:=True
ActiveSheet.ShowAllData
Columns("C:O").EntireColumn.Hidden = False
Columns("M:M").EntireColumn.Hidden = True
Columns("P:P").EntireColumn.Hidden = True
ActiveSheet.Pictures("Picture 1").Visible = True
End With
End Sub
Yes, it is possible. Add this to your code. It will ask the user to select a location to save the file.
Sub download_location()
Dim user As String
Dim fldr As FileDialog
Dim sItem As String
Dim getfolder As String
user = Application.UserName
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
getfolder = sItem
Set fldr = Nothing
'do something here
End Sub

VBA Code only fully works when using breakpoint

I am running into an issue with the code below. The "Cash Flow" sheet will not change the height to fit onto one page. When I use a breakpoint it works but that line seems to be skip when running the macro.I have tried using Application.Wait but that did not work. Any thoughts on how I can fix it? Thanks in advance!
Section of the code that is not working:
Sheets("Cash Flow").Select
With ActiveSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
Full Code:
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
`enter code here` If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Sets Page Height ad Width
Dim myArray() As Variant
Dim i As Integer
For i = 1 To Sheets.Count
ReDim Preserve myArray(i - 1)
myArray(i - 1) = i
Next i
Sheets(myArray).Select
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 0
End With
Sheets("Cash Flow").Select
With ActiveSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strName = CreateObject("Scripting.FileSystemObject").GetBaseName(ActiveWorkbook.Name)
'create default name for savng file
strFile = strName & ".pdf"
strPathFile = strPath & strFile
'export to PDF in current folder
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=strPathFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
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?

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