Combining multiple text files with same header format using excel VBA? - excel

I have multiple text files I need to combine
All have the same headers (with the exception of the Image name, but this will change in ascending order, with "HU1284 - Position 2.Blind", "HU1284 - Position 3.Blind" etc), but varying numbers of rows of information within their dataset. I've been using an excel macro to combine them, but this requires separating each file in the program that generates the text files, and that takes ages. I'm trying to avoid that if possible. Would anyone be able to help me modify the VBA script below so that it can combine these text files as is? Thanks in advance!!
Public HeadLine As String
Public ThisLine As String
Public Checkfilenum
Public TotalRows
Public NDresults
Sub Comb_1()
' Comb_1 Macro Used to combine the text files together into a sindle result file if new data results
' in going over the row limit then attempt will be made to make a new dresult file by incrementing index.
' will loop through until a valid dresults file can be made.
nbook = ActiveWorkbook.Name
'checkfor opened dresults workbook
wcnt = 0
For Each w In Workbooks
If UCase(w.Name) Like "DRESULT*" Then
wcnt = 1
w.Activate
End If
Next
If wcnt = 1 And HeadLine = "FirstOne" Then HeadLine = ThisLine
' CHeck if adding new file will exceed 65536 limit of Excel (may need to change for 2007)
Call MaxNumRowscheck(nbook, wcnt)
' If dresults file is not opened then create it from thie file (nbook)
If wcnt = 0 Then
'Check if this is the first file in this run so we have line 6 to compare against.
If HeadLine = "FirstOne" Then HeadLine = ThisLine
On Error GoTo exitsub
' create dresults (note will check for existance of one just in case.)
ActiveWorkbook.SaveAs Filename:="dresults.xlsm", FileFormat:=xlNormal
Workbooks("dresults.xlsm").Activate
' prep sheet
Sheets(1).Name = "Combined data"
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=True, Other:=True, OtherChar:= _
"_", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1)) _
, TrailingMinusNumbers:=True
Range("A3").Select
Selection.TextToColumns Destination:=Range("A3"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=True, Other:=False, OtherChar _
:="_", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Range("A4").Select
Columns("A:A").Select
Selection.Insert Shift:=xlToRight
Selection.Insert Shift:=xlToRight
Selection.Insert Shift:=xlToRight
Selection.Insert Shift:=xlToRight
Selection.Insert Shift:=xlToRight
Range("G1:J1").Select
Selection.Cut
Range("A8").Select
ActiveSheet.Paste
Range("G3").Select
Selection.Cut
Range("E8").Select
ActiveSheet.Paste
Rows("1:6").Select
Selection.Delete Shift:=xlUp
Range("A2:E2").Select
Selection.Copy
Range(Selection, Selection.End(xlDown)).Select
Selection.FillDown
Selection.End(xlDown).Select
ActiveCell.Offset(0, 5).Range("A1").Select
Selection.End(xlUp).Select
ActiveCell.Offset(1, -1).Range("A1").Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Delete Shift:=xlUp
Range("A1").Select
ActiveCell.FormulaR1C1 = "Exp_Round"
Range("B1").Select
ActiveCell.FormulaR1C1 = "Within_Round_Pair"
Range("C1").Select
ActiveCell.FormulaR1C1 = "Within_Pair_Imaged_Seq"
Range("D1").Select
ActiveCell.FormulaR1C1 = "Image_Number"
Range("E1").Select
ActiveCell.FormulaR1C1 = "Mask"
Range("A1").Select
ElseIf ThisLine = HeadLine Then
' repeat work above but for files just being prepared and appended
' using the previously started dresults file

Related

Excel macro to select next/previous file in folder

I have a macro that imports a txt file and displays some XY co-ordinates in a scatter graph. I'd like to be able choose a folder then hit next/back to view the other files in the folder rather than select each file individually.
This is the macro, each time I select the file, it pastes the XY values into the relevant place on the sheet (I have to do it this way to pick out the columns I need from the source data). The tool is useful but would be 10x better if I could hit one button to see the next file as I often have 30+ files to check
Public Sub TxtToCol()
'Step1: delete existing contents
Columns("A:j").Select
Selection.ClearContents
Range("A1").Select
'Updated to include ImportText macro into main code
Dim textFileNum, rowNum, colNum As Integer
Dim textFileLocation, textDelimiter, textData As String
Dim tArray() As String
Dim sArray() As String
textFileLocation = Application.GetOpenFilename()
'If no file selected stop macro
If textFileLocation = False Then Exit Sub
textDelimiter = ","
textFileNum = FreeFile
Open textFileLocation For Input As textFileNum
textData = Input(LOF(textFileNum), textFileNum)
Close textFileNum
tArray() = Split(textData, vbLf)
For rowNum = LBound(tArray) To UBound(tArray) - 1
If Len(Trim(tArray(rowNum))) <> 0 Then
sArray = Split(tArray(rowNum), textDelimiter)
For colNum = LBound(sArray) To UBound(sArray)
ActiveSheet.Cells(rowNum + 1, colNum + 1) = sArray(colNum)
Next colNum
End If
Next rowNum
'MsgBox "Data Imported Successfully", vbInformation
'Find XY co-ordinates, text to columns with 'space' delimiter, select full range then cut and paste into new area
Cells.Find(What:="+00.000", After:=ActiveCell, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
Range(Selection, Selection.End(xlDown)).Select
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=True, Other:=False, OtherChar _
:="=", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), _
TrailingMinusNumbers:=True
Range(Selection, Selection.End(xlToRight)).Select
Selection.Cut
Range("D9").Select
ActiveSheet.Paste
'Now co-ords are moved, remaining data can be delimited by '='
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="=", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
'Add updated cant formula to avoid Vlookup error
Range("U5").Formula = (Range("E9") - Range("E10")) * 1000
'Return to cell A1
Range("A1").Select
'MsgBox "Data Imported Successfully", vbInformation
End Sub

Multiple Excel Files Data extraction

I have a little issue with my code.
The purpose is to get a specific range of data from each file, and to copy that range to another file's gathering sheet named "Extraction".
The issue is that my code didn't copy and paste every single peace of data range below the previous piece of data, as it should be. Can you please help me with that one and give me a correction/add for my code. Thank you in advance!
Here's the code :
Sub Extraction()
Dim FileNames As Variant
Dim i As Integer
Application.ScreenUpdating = False
Range("A2").Select
FileNames = Application.GetOpenFilename(FileFilter:="Excel Filter (*csv), *.csv", Title:="OpenFile(s)", MultiSelect:=True)
For i = 1 To UBound(FileNames)
Workbooks.Open FileNames(i)
'Separate
Columns("A:A").Select
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:=";", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, _
1), Array(6, 1)), TrailingMinusNumbers:=True
Range("F19:F42").Select
Selection.Copy
Windows("Wind Energy Monthly Forecast.xlsm").Activate
Sheets("Extraction").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteAll, Transpose:=False
Workbooks.Open FileNames(i)
ActiveWorkbook.Close SaveChanges:=False
ActiveCell.Offset(1, 0).Activate
Next i
End Sub

Unable to execute Text to column using VBA code

I have written some code that performs a data collation task, but there is an issue as the raw data date format is dd-mm-yyyy. Manually, we can do text to column and change it using delimit date mm-dd-yyyy, the code for which I have shared below. However, it is not functioning properly after testing by step into F8 F8 F8 I saw text to column is not happening.
Code:-
Sub Compiling_Of_Data()
'''' Disbaling the screen update and refreshing for fast processing ''''
Application.ScreenUpdating = False
'''' Declaring the names as variables for all Raw file as (RF) and Main working file as (MWF) and their paths ''''
Dim RF1, RF2, RF3, RF4, RF5, RF6, RF7, RF8, RF9, RF10, RF11, RF12, RF13 As Variant
Dim MWF, MWF1, path, path1 As String
path = "C:\Users\Kunal.Khaire\Desktop\My Daily Task\202 - 203 POD KPI DASHBOARD\"
path1 = "C:\Users\Kunal.Khaire\Desktop\My Daily Task\202 - 203 POD KPI DASHBOARD\Raw Dump\"
'''' Variable assigned ''''
MWF = "1 POD KPI Dashboard - Template.xlsb"
RF1 = "1_Mastersheet_crosstab.csv"
RF2 = "2_Toggle_Count_crosstab.csv"
RF3 = "3_Agent_Disconnection_crosstab.csv"
RF4 = "4_Quiz_Level_crosstab.csv"
RF5 = "5_Overall_Performance_(2)_crosstab.csv"
RF6 = "6_Overall_Performance_(3)_crosstab.csv"
RF7 = "7_Overall_Performance_(4)_crosstab.csv"
RF8 = "8_Overall_Performance_(5)_crosstab.csv"
RF9 = "9_OB_Calls_not_Tagged_crosstab.csv"
RF10 = "10_LB_Tagged_Dump_crosstab.csv"
RF11 = "11_Call_Not_Answered_crosstab.csv"
RF12 = "12_tNPS_crosstab.csv"
RF13 = "13_Nulceus.csv"
Workbooks.Open (path & MWF)
'''' below code delete old data if any ''''
Sheets("Nucleus Dum 213").Select
Rows("4:1048576").Select
Selection.Delete Shift:=xlUp
Range("A1").Select
Sheets("Mastersheet").Select
Rows("5:1048576").Select
Selection.Delete Shift:=xlUp
Range("A2").Select
Sheets(Array("Tnps Raw", "Quality Dump (2)", "Quality Dump (3)", _
"Quality Dump (4)", "Quality Dump (5)", "OB Calls not Tagged", _
"Quiz_Level_crosstab (2)", "Toggling", "Agent Disconnection", _
"Call Not Answered", "Tagged Dump")).Select
Rows("4:1048576").Select
Selection.Delete Shift:=xlUp
Range("A1").Select
Sheets("Nucleus Dum 213").Select
Range("A1").Select
'''' pasting "TNPS Data" in our working file ''''
Workbooks.Open (path1 & RF12)
Range("A1").Select
ActiveCell.Offset(1, 0).Range("A1").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.Copy
Workbooks(MWF).Activate
Sheets("Tnps Raw").Select
Range("A1").Select
ActiveCell.Offset(1, 1).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
ActiveCell.Offset(0, 1).Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, -1).Range("A1").Select
Range(Selection, Selection.End(xlUp)).Select
Application.CutCopyMode = False
Selection.FillDown
Columns("B:B").Select
Selection.TextToColumns Destination:=Range("B:B"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 3), TrailingMinusNumbers:=True
Range("A1").Select
'

How to find the next available column and apply a formula to it

I'm trying to change my designated column "J" to a variable (the next free column on row 5) as sometimes J is in use. Then apply the formula to that column and copy it, inserting after Column A. I know that I need to set the value for the last column, but I'm not sure how to bring it all together for my formula. The formula generally works well until data is introduced to Column J or K, then it pastes over it.
Range("J5").Select
ActiveCell.FormulaR1C1 = "=RIGHT(RC[-2], 6)"
Selection.AutoFill Destination:=Range("J5:J" & Range("E" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select
Columns("B:B").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A5").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.TextToColumns Destination:=Range("A5"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
:=Array(Array(1, 3), Array(2, 3), Array(3, 3)), TrailingMinusNumbers:=True
Range("B5").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.NumberFormat = "dd/mm/yyyy;#"
Selection.TextToColumns Destination:=Range("B5"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
:=Array(1, 8), TrailingMinusNumbers:=True
Columns("B:B").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("M5").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Range("B5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks _
:=False, Transpose:=False
End Sub
You can accomplish this by starting at Range("I5") and using Resize and Offset to insert the formula into the range without using AutoFill.
The code below is a one-liner.
Note: you subtract the 4 and 8 to account for the rows and columns from the strtCel
ActiveSheet. _
Range("I5").Resize(ActiveSheet.Range("E" & Rows.Count).End(xlUp).Row - 4, 1). _
Offset(, ActiveSheet.Cells(5, Columns.Count).End(xlToLeft).Column - 8). _
FormulaR1C1 = "=RIGHT(RC8, 6)"
You can also use variables
Dim ws As Worksheet, lRow As Long, eCol As Long, strtCel As Range
Set ws = ThisWorkbook.Sheets("Sheet1") 'Change worksheet name as needed
Set strtCel = ws.Range("I5")
lRow = ws.Range("E" & ws.Rows.Count).End(xlUp).Row
eCol = ws.Cells(5, ws.Columns.Count).End(xlToLeft).Column
With strtCel.Resize(lRow - 4, 1).Offset(, eCol - 8)
.FormulaR1C1 = "=RIGHT(RC8, 6)"
.Value = .Value
End With

Excel VBA transposing issues

I'm trying to perform a do while loop that takes 3 cells, splits them, takes the right split and transposes it. Then move down to the next set of 3. Here's what I have
Sub transposer2()
Dim i As Integer
Do While i < 300
Range(ActiveCell, ActiveCell.Offset(2, 0)).Select
Selection.TextToColumns Destination:=ActiveCell.Offset(0, 1).Select, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:=":", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Range(ActiveCell, ActiveCell.Offset(2, 0)).Select
Selection.Copy
Range(ActiveCell.Offset(0, 1)).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, transpose:=True
Application.CutCopyMode = False
ActiveCell(9, -3).Select
Loop
End Sub
The selection after the range selection is where I am having trouble.
This is the data I copy from a txt file and ends up being space 9 rows apart
TAPER ANGLE : 6.6297
GAGE POINT DIA : 0.1775
DEPTH OF TAPER : -0.5950
give this a try. It uses the split function rather than text to columns.
Sub Transposer()
Dim MySpl
SplitAgain:
For x = 0 To 2
MySpl = Split(ActiveCell.Offset(x, 0).Value, " : ")
ActiveCell.Offset(0, x + 1).Value = MySpl(1)
Next
If ActiveCell.Offset(3, 0).Value <> "" Then
ActiveCell.Offset(3, 0).Select
GoTo SplitAgain
End If
End Sub

Resources