Issue with loading multiple comma delaminated text in excel using VBA - vba

Good morning,
I am trying to load multiple comma delaminated casv style file with .plt extension in excel with.
What I am trying to do is to load openfolder dialogue and select the folder where my codes are saved wit the first bit of code and paste the path in TextBox1. I have managed to successfully do that.
Then I am trying to run further codes with the run button to load all files in a new workbook with filenames as sheet name. But I am struggling with the following 2 things:
When I try to open the file in new workbook, each file opening in new workbook but I want them to just open 1 new workbook with each files in different worksheets.
The program works fine when I manually assign directory path but when I ask the program to read the folder path where the files are saved from the textbox its failing
Could someone please give me some advise on how to rectify this, many thanks. My codes are as follows:
I have added comments on possibly where I think I am doing something wrong as by replacing the commented sections manually with the file path sich as "C:\Users\Desktop\test\" the program works fine to load in same workbook all files.
'Code for the button on the right of textbox 1
Private Sub FilePath_Button_Click()
get_folder
End Sub
' code for the run button
Private Sub Run_Button_Click()
load_file
End Sub
Private Sub TextBox1_Change()
End Sub
Private Sub UserForm_Click()
End Sub
'code for the fild open dialouge box to locate folder where the files are saved
Public Sub get_folder()
Dim FolderName As String
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
On Error Resume Next
FolderName = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End With
TextBox1.Text = FolderName
End Sub
'codes for the run button to import the files
Sub load_file()
Dim strFile As String
Dim ws As Worksheet
strFile = Dir("TextBox1.Text*.plt") ' I think this is the bit where I doing something wrong
Do While strFile <> vbNullString
Set ws = Sheets.Add
With ws.QueryTables.Add(Connection:= _
"TEXT;" & "TextBox1.Text" & strFile, Destination:=Range("$A$1")) ' and also "TextBox1.Text" I think not right as if i replace this two section that I commented with the file path manually the program works fine
.Name = strFile
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
strFile = Dir
Loop
End Sub

Try replacing:
strFile = Dir("TextBox1.Text*.csv") ' I think this is the bit where I doing something wrong
Do While strFile <> vbNullString
Set ws = Sheets.Add
with
StrFile = Dir(Me.TextBox1.Text & "\*.csv")
Do While Len(StrFile) > 0
Set ws = ActiveWorkbook.Sheets.Add
ws.Name = StrFile
EDIT
To add the .csv files to new workbooks
Dim wb as workbook
Do While Len(StrFile) > 0
Set wb = Workbooks.Add
'added workbook becomes the activeworkbook
Set ws = ActiveWorkbook.Sheets.Add
ws.Name = StrFile

Is there any reason you are using a QueryTable? Just opening the workbook and copying the sheet should suffice as the CSV file will already have the sheetname as the filename.
Try replacing the load_file() procedure with this:
Sub load_file()
Dim wb1 As Workbook, wb2 As Workbook
Dim filePath As String, strFile As String
Application.ScreenUpdating = False
Set wb1 = ActiveWorkbook
filePath = TextBox1.Text
strFile = Dir(filePath)
While Not strFile = ""
If LCase(Right(strFile, 4)) = ".plt" Then
Set wb2 = Workbooks.OpenText(Filepath:=fileName & "\" & strFile, Datatype:=xlDelimited, Comma:=True) '// open the workbook
wb2.Sheets(1).Copy after:=wb1.Sheets(wb1.Sheets.Count) '// copy the page to wb1
wb2.Close False '// close wb2
Set wb2 = Nothing '// release from memory
End If
strFile = Dir()
Wend
Set wb1 = Nothing
Application.ScreenUpdating = True
MsgBox "Done"
End Sub

Related

Runnig a .bat file from within VB

In Win 10 while running an Excel program, I have a button which executes a VB. module. In the module is the statement Process.Start ("Batfile.bat"). Batfile.bat is in the same directory as the Excel file. Batfile's contents are simply
pause
msg * List Created!
Here is the full code:
Sub Worksheets_to_txt()
'<--Saves each worksheet as a text file with the same name
Dim CalcState As Long
Dim EventState As Boolean
Dim PageBreakState As Boolean
Application.ScreenUpdating = False
' EventState = Application.EnableEvents
' Application.EnableEvents = False
CalcState = Application.Calculation
Application.Calculation = xlCalculationManual
PageBreakState = ActiveSheet.DisplayPageBreaks
ActiveSheet.DisplayPageBreaks = False
Dim ws As Worksheet
Dim relativePath As String
Dim answer As VbMsgBoxResult
relativePath = ActiveWorkbook.Path
' answer = MsgBox("Are you sure you want to export worksheets?", vbYesNo, "Run Macro") '<--Pop up box to confirm export
Process.Start ("Batfile.bat")
' If answer = vbYes Then
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each ws In ActiveWorkbook.Worksheets
ws.Select
ws.Copy
ActiveWorkbook.SaveAs Filename:= _
relativePath & "\" & ws.Name & ".txt", _
FileFormat:=xlText, CreateBackup:=False
ActiveWorkbook.Close
ActiveWorkbook.Activate
Next
Worksheets("Master").Activate
MsgBox "Text files have been created."
' End If
ActiveSheet.DisplayPageBreaks = PageBreakState
Application.Calculation = CalcState
' Application.EnableEvents = EventState
Application.ScreenUpdating = True
End Sub
This runs fine when I execute it outside of Excel by itself, but pushing the button in excel gives me
Run-time error "424":
Object Required
I have tried a number of online remedies, but I keep getting the same result. What am I doing wrong?
System.Diagnostics.Process.Start() should work ideally. Please try by providing absolute path.

Import multiple text files into single worksheet

I found the following code which imports each text file into a separate worksheet and it worked perfectly. Is there a way to modify the code so ALL text files are imported into a SINGLE worksheet?
I'm using Excel 2013 on Windows7 64 bit if that makes a difference.
Sub ImportTXTFiles()
Dim fso As Object
Dim xlsheet As Worksheet
Dim qt As QueryTable
Dim txtfilesToOpen As Variant, txtfile As Variant
Application.ScreenUpdating = False
Set fso = CreateObject("Scripting.FileSystemObject")
txtfilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
For Each txtfile In txtfilesToOpen
' FINDS EXISTING WORKSHEET
For Each xlsheet In ThisWorkbook.Worksheets
If xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "") Then
xlsheet.Activate
GoTo ImportData
End If
Next xlsheet
' CREATES NEW WORKSHEET IF NOT FOUND
Set xlsheet = ThisWorkbook.Worksheets.Add( _
After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "")
xlsheet.Activate
GoTo ImportData
ImportData:
' DELETE EXISTING DATA
ActiveSheet.Range("A:Z").EntireColumn.Delete xlShiftToLeft
' IMPORT DATA FROM TEXT FILE
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & txtfile, _
Destination:=ActiveSheet.Cells(1, 1))
.TextFileParseType = xlDelimited
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "|"
.Refresh BackgroundQuery:=False
End With
For Each qt In ActiveSheet.QueryTables
qt.Delete
Next qt
Next txtfile
Application.ScreenUpdating = True
MsgBox "Successfully imported text files!", vbInformation, "SUCCESSFUL IMPORT"
Set fso = Nothing
End Sub
A lot of the code in here is dealing with creating new tabs etc. so that can go.
What you're left with is a loop that loads each text file into Cells(1,1) - so if we tweak that to point at a value which checks the last used cell in column A, then this should do what you need:
Sub ImportTXTFiles()
Dim fso As Object
Dim xlsheet As Worksheet
Dim qt As QueryTable
Dim txtfilesToOpen As Variant, txtfile As Variant
Application.ScreenUpdating = False
Set fso = CreateObject("Scripting.FileSystemObject")
txtfilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
With ActiveSheet
For Each txtfile In txtfilesToOpen
importrow = 1 + .Cells(.Rows.Count, 1).End(xlUp).Row
' IMPORT DATA FROM TEXT FILE
With .QueryTables.Add(Connection:="TEXT;" & txtfile, _
Destination:=.Cells(importrow, 1))
.TextFileParseType = xlDelimited
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "|"
.Refresh BackgroundQuery:=False
End With
Next txtfile
For Each qt In .QueryTables
qt.Delete
Next qt
End With
Application.ScreenUpdating = True
MsgBox "Successfully imported text files!", vbInformation, "SUCCESSFUL IMPORT"
Set fso = Nothing
End Sub
Also, I notice you delete 'all' the query tables inside your loop. This isn't necessary. Just delete them all once they're all loaded.
I believe the following will do what you expect, this will bring all your text data into a single worksheet, it will check for the last row with data in Column A, and offset by one row to import data from the next Text File:
Sub ImportTXTFiles()
Dim fso As Object
Dim xlsheet As Worksheet
Dim qt As QueryTable
Dim LastRow As Long
Dim txtfilesToOpen As Variant, txtfile As Variant
Application.ScreenUpdating = False
Set fso = CreateObject("Scripting.FileSystemObject")
txtfilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
For Each txtfile In txtfilesToOpen
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1
' IMPORT DATA FROM TEXT FILE
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & txtfile, _
Destination:=ActiveSheet.Cells(LastRow, 1))
.TextFileParseType = xlDelimited
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "|"
.Refresh BackgroundQuery:=False
End With
For Each qt In ActiveSheet.QueryTables
qt.Delete
Next qt
Next txtfile
Application.ScreenUpdating = True
MsgBox "Successfully imported text files!", vbInformation, "SUCCESSFUL IMPORT"
Set fso = Nothing
End Sub

Find if workbook for individual user exists, if workbook does not exist, create a new workbook with template

I have a data file that I am trying to make for each person in my work group. The data file needs to be identical to a master file as each persons data will be collected into said master file as well as an individual data file.
So far, I have the following code where I try to identify whether a user already has a workbook. I want the created workbook to have the same first four sheets as the master workbook.
The folder specified only contains the "DataFile Master" Workbook so I wouldn't expect the macro to take longer than ~5 seconds. However, when I try to run the macro, the workbook becomes non responsive.
The program does not induce an error report or indicate something to debug.
Does anyone have any ideas?
Sub StoreToPersonal()
Application.ScreenUpdating = False
ckIndWkbk = False
folderpath = "\\netappa\Path\MACRO UPDATE WORKBOOKS" 'change to suit
If Right(folderpath, 1) <> "\" Then folderpath = folderpath + "\"
filename = Dir(folderpath & "*.xlsm")
'Look through path length and find if user has an individual Workbook with a Boolean Statement
Do While filename <> ""
If InStr(filename, Environ("Username")) Then
ckIndWkbk = True
Else
End If
Loop
If ckIndWkbk = False Then
Set wb = Workbooks.Open("\\netappa\Path\MACRO UPDATE WORKBOOKS\DataFile Master.xlsm")
ws = wb.Sheets.Count
For Each ws In wb
If ws.Index > 4 Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
wb.SaveAs ("\\netappa\Path\MACRO UPDATE WORKBOOKS\\DataFile For " & Environ("Username"))
End If
Application.ScreenUpdating = True
End Sub
The first Dir call sets the parameters and return the first file in the directory. You need to use the Dir in your Do Loop to return subsequent files.
Note: I added Exit Do to after the condition is met.
MSDN Dir Function
Sub StoreToPersonal()
Application.ScreenUpdating = False
ckIndWkbk = False
folderpath = "\\netappa\Path\MACRO UPDATE WORKBOOKS" 'change to suit
If Right(folderpath, 1) <> "\" Then folderpath = folderpath + "\"
Filename = Dir(folderpath & "*.xlsm")
'Look through path length and find if user has an individual Workbook with a Boolean Statement
Do While Filename <> ""
If InStr(Filename, Environ("Username")) Then
ckIndWkbk = True
Exit Do
End If
Filename = Dir
Loop
If ckIndWkbk = False Then
Set wb = Workbooks.Open("\\netappa\Path\MACRO UPDATE WORKBOOKS\DataFile Master.xlsm")
ws = wb.Sheets.Count
For Each ws In wb
If ws.Index > 4 Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
wb.SaveAs ("\\netappa\Path\MACRO UPDATE WORKBOOKS\\DataFile For " & Environ("Username"))
End If
Application.ScreenUpdating = True
End Sub

Merging multiple worksheets with Images into one workbook - Image error

I just started using VBA and I've been using a code to merge multiple worksheets into a single workbook, it works fine except for worksheets containing images. In these cases the image won't show in the new workbook created. It appears the box where the image should be with an error message. I use MS Office 2010.
Here follows the code I've been using:
Sub MergePlans()
Dim CurFile As String, DirLoc As String
Dim DestWB As Workbook
Dim ws As Object
DirLoc = ThisWorkbook.Path & "\Merge\"
CurFile = Dir(DirLoc & "*.xlsx")
Application.ScreenUpdating = False
Application.EnableEvents = False
Set DestWB = Workbooks.Add(xlWorksheet)
Do While CurFile <> vbNullString
Dim OrigWB As Workbook
Set OrigWB = Workbooks.Open(Filename:=DirLoc & CurFile, ReadOnly:=True)
For Each ws In OrigWB.Sheets
ws.Select
ws.Copy After:=DestWB.Sheets(DestWB.Sheets.Count)
Next
OrigWB.Close Savechanges:=False
CurFile = Dir
Loop
Application.DisplayAlerts = False
DestWB.Sheets(1).Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.EnableEvents = True
Set DestWB = Nothing
End Sub
Any idea of what is going on? I'd appreciate any help!
Tks!
just found a workaround that helped!
I just added "Application.ScreenUpdating = True" before closing the source workbook, it takes longer to merge all worsheets, but at least the images are displayed correctly!
Here follows the new code:
Sub MergePlans()
Dim CurFile As String, DirLoc As String
Dim DestWB As Workbook
Dim ws As Object
DirLoc = ThisWorkbook.Path & "\Merge\"
CurFile = Dir(DirLoc & "*.xlsx")
Application.ScreenUpdating = False
Application.EnableEvents = False
Set DestWB = Workbooks.Add(xlWorksheet)
Do While CurFile <> vbNullString
Dim OrigWB As Workbook
Set OrigWB = Workbooks.Open(Filename:=DirLoc & CurFile, ReadOnly:=True)
For Each ws In OrigWB.Sheets
ws.Select
ws.Copy After:=DestWB.Sheets(DestWB.Sheets.Count)
Next
**Application.ScreenUpdating = True**
OrigWB.Close Savechanges:=False
CurFile = Dir
Loop
Application.DisplayAlerts = False
DestWB.Sheets(1).Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.EnableEvents = True
Set DestWB = Nothing
End Sub
Found this workaround here - Option 1!
Tks Dan!

VBA Code Works in Excel 2010 But Not Excel 2013

I have code in VBA that copies worksheets with the same tab name from different workbooks into one workbook. The workbooks that the code pulls from is in one folder. The code is working fine in Excel 2010 however when I run it in Excel 2013, I get the following 1004 error message: "Sorry, we couldn't find ....xlsx. Is it possible it was moved, renamed or deleted." I'm not sure where to start troubleshooting. Has anyone run into this problem or have any ideas why it would be working fine in Excel 2010 and not Excel 2013? Thank you.
Sub CombineSheets()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim sPath As String
Dim sFname As String
Dim wBk As Workbook
Dim wSht As Variant
Application.EnableEvents = False
Application.ScreenUpdating = False
sPath = "PathName\Inputs"
ChDir sPath
sFname = "*"
sFname = Dir(sPath & "\" & sFname & ".xlsx*", vbNormal) <Code bombs here>
wSht = ("Risks")
Do Until sFname = ""
Set wBk = Workbooks.Open(sFname)
Windows(sFname).Activate
Sheets(wSht).Copy Before:=ThisWorkbook.Sheets(1)
wBk.Close False
sFname = Dir()
Loop
ActiveWorkbook.Save
Application.EnableEvents = True
Application.ScreenUpdating = True
Are you sure this code has previously worked?
If it did, then your application's default file path has probably changed. You can check this with Debug.Print Application.DefaultFilePath In any event, you'd be better off defining your full path name explicitly in your sPath variable.
If you want to pick up legacy Excel documents then the string in your Dir function could just be "*.xls*" (but that would also collect macro-enabled workbooks). I wonder if that was originally intended with the asterix in your code.
There's no need to activate the window, but you might want an error handling line to check whether the "Risks" sheet does exist in the workbook.
There's also some redundancy in your code, so the whole thing ought to work okay as given below:
Sub CombineSheets()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim sPath As String
Dim sFname As String
Dim wBk As Workbook
Dim wSht As Worksheet
Application.EnableEvents = False
Application.ScreenUpdating = False
sPath = "PathName\Inputs" 'make this a full path eg "C:\..."
sFname = Dir(sPath & "\" & "*.xls*", vbNormal)
Do Until sFname = ""
'skip if it's this workbook
If sFname <> ThisWorkbook.Name Then
Set wBk = Workbooks.Open(sPath & "\" & sFname)
'check a "Risks" sheet exists
Set wSht = Nothing
On Error Resume Next
Set wSht = wBk.Sheets("Risks")
On Error GoTo 0
If Not wSht Is Nothing Then
wSht.Copy Before:=ThisWorkbook.Sheets(1)
End If
wBk.Close False
End If
sFname = Dir()
Loop
ActiveWorkbook.Save
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub