VBA to convert text to columns in multiple sheets except one - excel

I am new in VBA coding and and am trying to convert text in all sheets except one to text but have not achieved success. I have text in column A of each sheet and number of rows might differ.
This is what my code looks like
Sub text_to_column()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim arr() As Variant, i As Long, nrCol As Long
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Summary" Then
ws.Select
nrCol = 20
ReDim arr(1 To nrCol) As Variant
For i = 1 To nrCol
arr(i) = Array(i, 1)
Next
Selection.TextToColumns _
Destination:=Range("A1"), _
DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=True, _
Semicolon:=False, _
Comma:=False, _
Space:=False, _
Other:=True, _
OtherChar:="^", _
FieldInfo:=arr, _
TrailingMinusNumbers:=True
End If
Next ws
End Sub
Please Guide.

Try this code
Sub Test()
Dim a, x, ws As Worksheet, r As Long
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Summary" Then
For r = 1 To ws.Cells(Rows.Count, 1).End(xlUp).Row
x = Split(ws.Cells(r, 1).Value, "^")
ws.Cells(r, 2).Resize(, UBound(x) + 1).Value = x
Next r
End If
Next was
End Sub
And as for your approach, you can use such a code
Sub TextToColumns()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Summary" Then
Application.DisplayAlerts = False
ws.Columns(1).TextToColumns Destination:=Range("B1"), DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar:="^", FieldInfo:=Array(Array(1, 1)), TrailingMinusNumbers:=True
Application.DisplayAlerts = True
End If
Next was
End Sub

Related

Attempting to continue my list import, instead it over overwrites my previous import in VBA

I've borrowed some code from a post on this site already and made my own. However I'm running into a problem where the multiple files in my folder path are importing OVER the previous import instead of below the created list.
What I'm trying to achieve is importing data from multiple files in a specific folder location. After pursing through each file, the next import data should be placed under the previous import data in the worksheet.
Any insights on how to fix?
Thanks so much!
cwegz
Option Explicit
Const FOLDER_PATH = "Test Folder Path/" 'REMEMBER END BACKSLASH
Sub ImportWorksheets()
'=============================================
'Process all Excel files in specified folder
'=============================================
Dim sFile As String 'file to process
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim rowTarget As Long 'output row
rowTarget = 2
'check the folder exists
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
'reset application settings in event of error
On Error GoTo errHandler
Application.ScreenUpdating = False
'set up the target worksheet
Set wsTarget = Sheet1
'loop through the Excel files in the folder
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
Set wsSource = wbSource.Worksheets(1) 'EDIT IF NECESSARY
'import the data
With wsTarget
.Columns("A").Value = wsSource.Columns("A").Value 'this one works
.Columns("B").Value = wsSource.Columns("C").Value 'this one works
'.Range("A1" & rowTarget).Value = wsSource.Columns("A").Value
'.Range("B1" & rowTarget).Value = wsSource.Columns("C").Value
'optional source filename in the last column
.Range("N" & rowTarget).Value = sFile
End With
'close the source workbook, increment the output row and get the next file
wbSource.Close SaveChanges:=False
rowTarget = rowTarget + 1
sFile = Dir()
Loop
errHandler:
On Error Resume Next
Application.ScreenUpdating = True
'tidy up
Set wsSource = Nothing
Set wbSource = Nothing
Set wsTarget = Nothing
Set Selection = Nothing
Sheets("Pull").Select
Columns("B:B").Select
Selection.TextToColumns Destination:=Range("C1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="#", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Set Selection = Nothing
Sheets("Pull").Select
Columns("D:D").Select
Selection.TextToColumns Destination:=Range("D1"), 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
Set Selection = Nothing
Sheets("WhiteList").Select
Columns("A:A").Select
Selection.TextToColumns Destination:=Range("K1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="#", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Set Selection = Nothing
Sheets("Summary").Select
End Sub
Here's one approach, which should work if your data tables are consistent and contain no blank rows/columns.
Option Explicit
Const FOLDER_PATH = "Test Folder Path\" 'REMEMBER END BACKSLASH
Sub ImportWorksheets()
Dim sFile As String 'file to process
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet, rngData As Range, numRows As Long
Dim rowTarget As Long 'output row
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
On Error GoTo errHandler
Application.ScreenUpdating = False
Set wsTarget = Sheet1
'get first empty row, assuming colA always has values
rowTarget = wsTarget.Cells(Rows.Count, 1).End(xlUp).Row + 1
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
Set wsSource = wbSource.Worksheets(1)
Set rngData = wsSource.Range("A1").CurrentRegion '<< assumes no empty rows/columns in your data table
numRows = rngData.Rows.Count '<<
With wsTarget
.Cells(rowTarget, "A").Resize(numRows, 1).Value = rngData.Columns(1).Value
.Cells(rowTarget, "B").Resize(numRows, 1).Value = rngData.Columns(3).Value
'etc etc
.Cells(rowTarget, "N").Value = sFile 'optional source filename in the last column
End With
wbSource.Close SaveChanges:=False
rowTarget = rowTarget + numRows '<<
sFile = Dir()
Loop
'snipped....
End Sub

VBA project Window runs Macro correct, however, Button on Sheet1 Does not

I have tested my macro many times through VBA Run Window, and all on Sheet2 appears correctly. When I try to run Macro from Button on Sheet1, two columns "C" and "D" raise all the numbers by one cell up. What could be the issue on Button, Sheet1?
At the same time, this script code has been arranged to delete content from empty rows with additional words, or letters, then it is suppose to delete a row up, perhaps, this could be the issue.
My code:
Sub CopyPasteintoSheet2()
Dim lr As Long
Dim i As Long
Dim inputdtae As Date
Dim rng As Range
lr = Cells(Rows.Count, 1).End(xlUp).Row
For i = lr - 0 To 2 Step -1
If Cells(i, "B") = "LLC" Then
Cells(i, "B").EntireRow.Delete
End If
Next i
ActiveWindow.SmallScroll Down:=11
Columns("J:J").Select
Selection.TextToColumns Destination:=Range("J1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Columns("R:R").Select
Selection.TextToColumns Destination:=Range("R1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Dim LastRow As Long
Dim NEWFORMAT As Worksheet
Dim Results As Worksheet
Set Results = Sheets("NEWFORMAT")
LastRow = Results.Cells(Results.Rows.Count, "Z").End(xlUp).Row
Range("A15:A400").Copy
Results.Range("A" & LastRow + 2).PasteSpecial xlValues
Range("B15:B400").Copy
Results.Range("B" & LastRow + 2).PasteSpecial xlValues
Range("J15:J400").Copy
Results.Range("C" & LastRow + 2).PasteSpecial xlValues
Range("R15:R400").Copy
Results.Range("D" & LastRow + 2).PasteSpecial xlValues
Application.DataEntryMode = False
End Sub

Calculating average of variable data size using VBA and Excel

I have task to upload multiple text files to multiple sheets and calculate average below that data.Some text files have 200 rows and some have 5 rows with
different number of data in each row.I have succesfully separate each file but i cannot make function average.Example of txt file: https://ufile.io/7ii41
Sub CombineTextFiles()
Dim xFilesToOpen As Variant
Dim I As Integer
Dim xWb As Workbook
Dim xTempWb As Workbook
Dim xDelimiter As String
Dim xScreen As Boolean
Dim lRow As Long
Dim lCol As Long
Dim Rws As Long
Dim Col As Integer
Dim r As Range
Dim FrNg As Range
On Error GoTo ErrHandler
xScreen = Application.ScreenUpdating
Application.ScreenUpdating = False
xFilesToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Open", , True)
If TypeName(xFilesToOpen) = "Boolean" Then
MsgBox "No files were selected", , "Error"
GoTo ExitHandler
End If
I = 1
Set xTempWb = Workbooks.Open(xFilesToOpen(I))
xTempWb.Sheets(1).Copy
Set xWb = Application.ActiveWorkbook
xTempWb.Close False
xWb.Worksheets(I).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=True, Space:=False, _
Other:=False
lRow = Cells.Find(what:="*", _
after:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
average=??
Do While I < UBound(xFilesToOpen)
I = I + 1
Set xTempWb = Workbooks.Open(xFilesToOpen(I))
With xWb
xTempWb.Sheets(1).Move after:=.Sheets(.Sheets.Count)
.Worksheets(I).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=True, Space:=False, _
Other:=False
End With
lRow = Cells.Find(what:="*", _
after:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
average=??
Loop
ExitHandler:
Application.ScreenUpdating = xScreen
Set xWb = Nothing
Set xTempWb = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description, , "Error"
Resume ExitHandler
End Sub
Here are two quick functions that you could add to your workbook that can calculate the average of a column.
Private Function ColumnAvg(colRng As Range)
ColumnAvg = 0
On Error Resume Next
ColumnAvg = Application.WorksheetFunction.Sum(Columns(colRng.Column)) / _
Application.WorksheetFunction.CountA(Columns(colRng.Column))
End Function
Private Function RowAvg(rowRng As Range)
RowAvg = 0
On Error Resume Next
RowAvg = Application.WorksheetFunction.Sum(Rows(rowRng.Row)) / _
Application.WorksheetFunction.CountA(Rows(rowRng.Row))
End Function
NOte: These are marked as private functions as they will calculate the ENTIRE column or row. These functions are meant to be called within VBA, not within the spreedsheet. Make sure you place these functions within the same module.
Example of code:
1 - x = ColumnAvg(Range("A1"))
2 - x = ColumnAvg(Range("A:A"))
3 - x = ColumnAvg(Cells(1,1))
If you are wanting to calculate the entire worksheet's average, then you could use this function...
Private Function AvgEverything()
Dim Text As String
Text = "A1:" & Split(Cells(1, ActiveSheet.Columns.Count).Address(True, False), "$")(0) _
& ActiveSheet.Rows.Count
AvgEverything = Application.WorksheetFunction.Sum(Range(Text)) / _
Application.WorksheetFunction.CountA(Range(Text))
End Function

How to extract text from between brackets?

I wrote VBA code that opens all of the .xls files in a folder, and copies and pastes desired information out of those files into a new workbook.
Each row in the new workbook is associated with a file from the folder.
Column1, Column2, Column3
FileName1, ABC, XYZ
FileName2, DEF, TUV
The info in Column3 has the formatting of
ArbitraryString1(Very_Important_Info)ArbitraryString2
Because I wanted Column3 to look nice, I iterated over every row and used
Range("C"&X).TextToColumns DataType:=xlDelimited, Other:=True _
OtherChar:="("
Columns("E:E").Insert Shift:=xlToRight *
Range("D"&X).TextToColumn DataType:=xlDelimited, Other:=True _
OtherChar:=")"
Range("C"&X).TextToColumns DataType:=xlDelimited, Other:=True _
OtherChar:="(" **
Columns("E:Z").Delete
Columns("C:C").Delete
*This is needed so when I call TextToColumn the second time I do not get a message asking if I want to overwrite what is already in that column.
I end up with
Column1, Column2, Column3
FileName1, ABC, Very_Important_Info_1
FileName2, DEF, Very_Important_Info_2
After calling OtherChar:="(" the first time I end up seeing
(Very_Important_Info)ArbitraryString2
with the left bracket still attached.
I call the method a second time or ColumnC would look like
(Very_Important_Info
Might work better with SPLIT
Sub TextToCols()
Dim rng As Range
Dim r As Range
Dim l As Long
Dim arr As Variant
With ActiveSheet
l = .Cells(.Rows.Count, "C").End(xlUp).Row
Set rng = Range("C2:C" & l)
For Each r In rng
r.Value = Application.WorksheetFunction.Substitute(r.Value, ")", "(")
arr = Split(r.Value, "(")
Cells(r.Row, 3).Value = arr(1)
Next r
End With
End Sub
Or text-to-columns:
Sub TextToCols()
Dim rng As Range
Dim r As Range
Dim l As Long
With ActiveSheet
l = .Cells(.Rows.Count, "C").End(xlUp).Row
Set rng = Range("C2:C" & l)
For Each r In rng
r.Value = Application.WorksheetFunction.Substitute(r.Value, ")", "(")
Next r
With .UsedRange.Columns("C").Cells
.TextToColumns Destination:=Range("C1"), _
DataType:=xlDelimited, _
OtherChar:="("
End With
End With
End Sub
Here is a simplified version of Michal Rosa's code:
Sub BeautifyIt()
With Worksheets("Sheet1")
With .Range("C2", .Range("C" & .Rows.Count).End(xlUp))
.Replace ")", "("
.TextToColumns Destination:=.Cells(1, 1), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, _
OtherChar:="(", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
End With
End With
End Sub

Text To Columns for variable number of lines

The code attached below is to split text to columns. I get an error when I run this code.
The data to be split is as follows:
NAME,1244
NAME,4356
NAME,5678
The number of lines with NAME is variable. I get run time error 1004, No data was selected to parse. How to solve this?
Sub SplitNameToColumns()
Dim rowCount As Long
rowCount = Cells(Rows.Count, "F").End(xlUp).Row
Range("F2").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)), _
TrailingMinusNumbers:=True
ActiveCell.Offset(1, 0).Select
Next Counter
End Sub
Try this:
Sub SplitAndScatter()
Dim LastRow As Long
LastRow = Cells(Rows.Count, "F").End(xlUp).Row
With Range("F2:F" & LastRow)
.TextToColumns Destination:=Range("F2"), DataType:=xlDelimited, Comma:=True
End With
End Sub
This is taken and modified from another question I answered here.
Let us know if this helps.

Resources