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
Related
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
I have a issue with copy/paste the data from one file to another after i changed the range of rows to be transferred. Until now i used a file with 147 rows and 6 columns, no i have to use a file with 579 rows in 6 columns. But when i try to transfer the data with the 549 rows i got the message : "There is already data here. Do you want to replaced it". It is very annoying and i don't know what's happening, while the data is in the same format, only the rows are much more. I think the Separate part is the problem, but not sure. Here's the part of the code, making that issue :
Sub OpenF()
Dim Window As String
Dim sPath As String
Dim VarName As String
Dim GetBook As String
Dim sFile As String
VarName = Sheet1.Range("a4").Value
Window = VarName & "FileName_3_15min.csv"
ChDir sPath & "\Schedule"
' Open the fail
sFile = sPath & "\Schedule\" & Window
If Dir(sFile) = "" Then
MsgBox "File: (" & Window & ") is missing"
Else
Workbooks.Open Filename:= _
sPath & "\Schedule\" & Window
Cells.Select
Selection.Copy
Windows(GetBook).Activate
Sheets("Sheet.5").Select
Cells.Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'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
Sheets("WindFarmBalchik_2.1").Columns("A:G").AutoFit
' Close the fail
Windows(Window).Activate
Application.CutCopyMode = False
ActiveWindow.Close SaveChanges:=False
End if
End Sub
I currently have a macro set up that allows me to paste data into column A from Textpad and then sorts, rounds, moves and saves the data as a txt file.
Is there anyway that I can modify the macro to allow me to import the txt file straight into Excel rather than having to copy and paste? The file names changes each time, but the file directory will stay the same.
This is the current macro I have that is run after manually copy and pasting the data into excel:
'Sub SortRoundandSave()
'
' SortTruncateandSave Macro
' This macro will sort, round and save your data
'
'
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), TrailingMinusNumbers:=True
Range("D1").Select
Selection.AutoFill Destination:=Range("D1:D" & Range("B" & Rows.Count).End(xlUp).Row)
Range("A:A,B:B,D:D").Select
Range("D1").Activate
Selection.Copy
Sheets("Truncated Data").Select
ActiveSheet.Paste
Sheets("Truncated Data").Select
Application.CutCopyMode = False
Sheets("Truncated Data").Move
ChDir "G:\XXXX\Folder\Name\ZZZZ\Sort"
ActiveWorkbook.SaveAs Filename:= _
"G:\XXXX\Folder\Name\ZZZZ\Sort\Sorted Data.txt", _
FileFormat:=xlText, CreateBackup:=False
Windows("Excel Truncator.xlsm").Activate
End Sub
I assume it needs a few lines before the text to columns part, but I cant seem to get one to work?
Any help would be greatly appreciated.
Thanks
Try this:
Sub SortRoundandSave()
'
' SortTruncateandSave Macro
' This macro will sort, round and save your data
'
Dim workSht As Worksheet: Set workSht = ActiveSheet 'ThisWorkbook.Sheets("") ' Enter the name of sheet
Dim FilePath As String
Dim strLine As String
Dim rowCnt As Long
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Select the file"
.Filters.Clear
.Filters.Add Description:="Text Files", Extensions:="*.txt"
'.InitialFileName = "G:\XXXX\Folder\Name" ' Optional: this is a startup directory, place the correct one and uncomment line
If .Show = 0 Then Exit Sub
FilePath = .SelectedItems(1)
End With
rowCnt = 1
Open FilePath For Input As #1
Do While Not EOF(1)
Line Input #1, strLine
workSht.Cells(rowCnt, 1) = strLine
rowCnt = rowCnt + 1
Loop
Close #1
With workSht
Range(.Cells(1, 1), .Cells(rowCnt - 1, 1)).TextToColumns Destination:=.Cells(1, 1), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), TrailingMinusNumbers:=True
.Cells(1, 4).AutoFill Destination:=Range(.Cells(1, 4), .Cells(workSht.Cells(Rows.Count, 2).End(xlUp).Row, 4)) ' "D1:D" & Range("B" & Rows.Count).End(xlUp).Row)
Range(.Cells(1, 1), .Cells(1, 4)).EntireColumn.Copy Sheets("Truncated Data").Cells(1, 1)
End With
Sheets("Truncated Data").Move
ActiveWorkbook.SaveAs Filename:= _
"G:\XXXX\Folder\Name\ZZZZ\Sort\Sorted Data.txt", _
FileFormat:=xlText, CreateBackup:=False
workSht.Parent.Activate
End Sub
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
I have this code to split strings. Currently if the counter is equal to the number of rows on which data is present, it will run properly. However, this number of rows is variable. How do I make the for loop run for as long there is data?
Sub SplitToColumns()
Range("A1").Select
For Counter = 0 To 100 Step 1
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, Comma:=True, Space:=False, _
Other:=False, _
FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), _
TrailingMinusNumbers:=True
ActiveCell.Offset(1, 0).Select
Next Counter
End Sub
Something like this:
get the row number of the last populated row in column A. (Replace with the column of your choice). Then use that row number in the for-loop, but start with 1, not with zero. Remove the debug.print if no longer required.
Sub SplitToColumns()
Dim rowCount As Long
rowCount = Cells(rows.Count, "A").End(xlUp).Row
Debug.Print rowCount
Range("A1").Select
For Counter = 1 To rowCount Step 1
Selection.TextToColumns Destination:=ActiveCell, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, Comma:=True, Space:=False, _
Other:=False, _
FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), _
TrailingMinusNumbers:=True
ActiveCell.Offset(1, 0).Select
Next Counter
End Sub
There are several other ways to make this code more efficient. For example, you don't need to select the cell before you do a TextToColumns. In fact, you can do a TextToColumns on a range of cells, you don't need to loop through all the cells in the range.
Use the technique above to get the row number of the last row, and then build a range starting in A1 and extending to column A, last populated row number.
Then perform a TextToColumns on the whole range, all in one go. Much, much faster than looping!!!
Sub SplitToColumns()
Dim rowCount As Long
Dim ws As Worksheet
'~~> Change this to the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
rowCount = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range("A1:A" & rowCount).TextToColumns _
Destination:=.Range("A1"), _
DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=True, _
Space:=False, _
Other:=False, _
FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), _
TrailingMinusNumbers:=True
End With
End Sub