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
Related
So, I'm importing several Japanese UTF-8 files into excel with the below VBA script, but the Japanese characters don't show up well when imported, and I can't exactly figure out where to put this command into the script:
.TextFilePlatform = 65001
How can I import the multiple text files with UTF-8 encoding to ensure the characters are displayed correctly?
This is the script i'm talking about btw
Sub CombineTextFiles()
'updateby Extendoffice
Dim xFilesToOpen As Variant
Dim I As Integer
Dim xWb As Workbook
Dim xTempWb As Workbook
Dim xDelimiter As String
Dim xScreen As Boolean
On Error GoTo ErrHandler
xScreen = Application.ScreenUpdating
Application.ScreenUpdating = False
xDelimiter = "|"
xFilesToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Kutools for Excel", , True)
If TypeName(xFilesToOpen) = "Boolean" Then
MsgBox "No files were selected", , "Kutools for Excel"
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:=False, Space:=False, _
Other:=True, OtherChar:="|"
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:=False, Space:=False, _
Other:=True, OtherChar:=xDelimiter
End With
Loop
ExitHandler:
Application.ScreenUpdating = xScreen
Set xWb = Nothing
Set xTempWb = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description, , "Kutools for Excel"
Resume ExitHandler
End Sub
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
I am making a macro that Optimizes the sheet by deleting unused ranges that create very large file sizes. It does this by finding the last used row (column), selecting a range from that last used row (column) to the very bottom-right) of the sheet, and clearing formats and deleting those cells, to delete the unused range that is taking up space.
E.g. if last used row is 50, select range A50 to Bottom right of sheet (aka XFD104873, clear those formats and delete range
I have been able to do this with rows, but not with columns. In the below code, I get a syntax error (shown as 'SYNTAX ERROR' below) when case 2 runs, and I can't for the life of me figure out why.
I need to use R1C1 notation but for some reason the range(cells(#,#)) aren't picking it up properly.
I think it has to do with the second part in which I do range(cells(#,#)).End(xlDown).end(Toright)
Let me know if i can provide any additional information!
Nick
'Option Explicit
Sub Optimize()
'Call OptimizeSheet(1, "HR_Data")
Call OptimizeSheet(2, "DomesticAsset_Data")
'Call OptimizeSheet(3, "InternationalAsset_Data")
End Sub
Sub OptimizeSheet(ByVal choice As Long, ByVal sht As String)
' 1 = Rows
' 2 = Columns
' 3 = Both
If WorksheetExists(sht) = False Then
MsgBox "Worksheet doesn't exist, check macro code"
Exit Sub
End If
'Workbook
Dim wb As Workbook
'Last Row and Column Variables
Dim lr As Long
Dim lc As Long
'File Size variables
Dim aFileSize As Long
Dim bFileSize As Long
Dim chngFileSize As Long
Set wb = Application.ActiveWorkbook
On Error GoTo errHandler
'Get file size before optimizing
aFileSize = FileLen(Application.ActiveWorkbook.FullName)
Select Case choice
'Rows
Case 1:
lr = Worksheets(sht).Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
With Worksheets(sht).Range("A" & lr, Range("A" & lr).End(xlDown).End(xlToRight))
.ClearFormats
.Delete
End With
'Columns
Case 2:
lc = Worksheets(sht).Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
SYNTAX ERROR HERE
With Worksheets(sht).Range(Cells(1, lc), RangeCells(1, lc).End(xlDown).End(xlToRight))
.ClearFormats
.Delete
End With
'Both
Case 3:
lr = Worksheets(sht).Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
With Worksheets(sht).Range("A" & lr, Range("A" & lr).End(xlDown).End(xlToRight))
.ClearFormats
.Delete
End With
'chnge
lc = Worksheets(sht).Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
With Worksheets(sht).Range(Cells(1, lc).Address(), Range(Cells(1, lc).Address()).End(xlDown).End(xlToRight))
.ClearFormats
.Delete
End With
Case Else:
MsgBox "Wrong Choice, check macro code"
End Select
Application.ThisWorkbook.Save
bFileSize = FileLen(Application.ActiveWorkbook.FullName)
If aFileSize + bFileSize = 0 Then
MsgBox "error in filesize"
End If
chngFileSize = bFileSize - aFileSize
If chngFileSize = 0 Then
MsgBox (sht & " already optimized")
Else
MsgBox ("Done. " & (chngFileSize / 1000) & "MB Saved")
End If
Exit Sub
errHandler:
MsgBox "error on line" & Erl
End Sub
Function WorksheetExists(shtName As String, Optional wb As Workbook) As
Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
WorksheetExists = Not sht Is Nothing
End Function
To delete columns:
With Worksheets(sht)
.Range(.Cells(1, lc + 1), _
.Cells(1, lc +1 ).End(xlToRight)).EntireColumn.Delete
End With
I have been trying to figure out how to take several hundred tab-delimited text files and import the data into subsequent columns of a single excel worksheet. The text files contain I(V) data with two columns and a header. I have found code/manipulated it to be able to remove the header and import into individual worksheets within a workbook but would like to be able to get the two columns of data from each worksheet into a single worksheet (i.e. columns from first text file to columns A & B of one worksheet, columns from second text file to columns C & D, etc.). Here is the code I am currently using:
Sub CombineTextFiles()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
wkbTemp.Sheets(1).Copy
Set wkbAll = ActiveWorkbook
wkbTemp.Close (False)
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=True, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
Rows("1:20").Select
Selection.Delete Shift:=xlUp
x = x + 1
While x <= UBound(FilesToOpen)
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
With wkbAll
wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
Rows("1:20").Select
Selection.Delete Shift:=xlUp
End With
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
Here is an example of one of my I(V) data files:
Notes:
Timestamp: 7/19/2018 8:36:11 AM
Channel: Channel A
NPLC: 1
Current Limit: 0.010000
Pulse Mode: 0
Bias Pulses: 1
Bias Level: 0.000000
Settling Time: 0.500000
Voltage (V) Current (A)
-1.00000E+0 -6.95885E-7
-9.50000E-1 -6.47828E-7
-9.00000E-1 -6.06955E-7
-8.50000E-1 -5.53913E-7
-8.00000E-1 -5.00038E-7
-7.50000E-1 -4.51646E-7
-7.00000E-1 -4.02903E-7
-6.50000E-1 -3.58851E-7
-6.00000E-1 -3.19926E-7
-5.50000E-1 -2.73332E-7
-5.00000E-1 -2.33349E-7
-4.50000E-1 -1.99018E-7
-4.00000E-1 -1.62825E-7
-3.50000E-1 -1.31703E-7
-3.00000E-1 -1.04510E-7
-2.50000E-1 -8.06238E-8
-2.00000E-1 -5.88286E-8
-1.50000E-1 -4.14340E-8
-1.00000E-1 -2.58151E-8
-5.00000E-2 -1.24138E-8
0.00000E+0 5.52116E-11
5.00000E-2 1.26769E-8
1.00000E-1 2.64685E-8
1.50000E-1 4.17401E-8
2.00000E-1 5.97095E-8
2.50000E-1 7.98343E-8
3.00000E-1 1.02119E-7
3.50000E-1 1.28176E-7
4.00000E-1 1.57270E-7
4.50000E-1 1.89915E-7
5.00000E-1 2.29916E-7
5.50000E-1 2.72104E-7
6.00000E-1 3.35173E-7
6.50000E-1 4.53464E-7
7.00000E-1 6.12379E-7
7.50000E-1 7.97423E-7
8.00000E-1 9.75624E-7
8.50000E-1 1.16841E-6
9.00000E-1 1.34435E-6
9.50000E-1 1.52710E-6
1.00000E+0 1.75166E-6
1.00000E+0 1.81262E-6
9.50000E-1 1.72918E-6
9.00000E-1 1.63206E-6
8.50000E-1 1.52714E-6
8.00000E-1 1.42523E-6
7.50000E-1 1.32162E-6
7.00000E-1 1.21624E-6
6.50000E-1 1.11347E-6
6.00000E-1 1.00770E-6
5.50000E-1 9.05824E-7
5.00000E-1 8.08058E-7
4.50000E-1 7.09499E-7
4.00000E-1 6.14927E-7
3.50000E-1 5.26256E-7
3.00000E-1 4.38557E-7
2.50000E-1 3.53943E-7
2.00000E-1 2.74731E-7
1.50000E-1 1.98096E-7
1.00000E-1 1.27457E-7
5.00000E-2 6.16247E-8
0.00000E+0 -8.63841E-11
-5.00000E-2 -5.78634E-8
-1.00000E-1 -1.15769E-7
-1.50000E-1 -1.73858E-7
-2.00000E-1 -2.33503E-7
-2.50000E-1 -2.94364E-7
-3.00000E-1 -3.59336E-7
-3.50000E-1 -4.24816E-7
-4.00000E-1 -4.92460E-7
-4.50000E-1 -5.61514E-7
-5.00000E-1 -6.32542E-7
-5.50000E-1 -7.06702E-7
-6.00000E-1 -7.83559E-7
-6.50000E-1 -8.63077E-7
-7.00000E-1 -9.49685E-7
-7.50000E-1 -1.03839E-6
-8.00000E-1 -1.12932E-6
-8.50000E-1 -1.22503E-6
-9.00000E-1 -1.31770E-6
-9.50000E-1 -1.42892E-6
-1.00000E+0 -1.53654E-6
None of the header information is needed, which is why I am currently just deleting the first 20 rows. I have basic programming experience but very little with VBA. Any help with this particular problem is greatly appreciated!
-Tory
Try so:
Sub CombineTextFiles()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
Set wkbAll = ActiveWorkbook
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
iDestCol=1
For x = 0 to Ubound(FilesToOpen)
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
wkbTemp.Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=True, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
wbkTemp.Range("A:B").Copy Destination:=wkbAll.Cells(1, iDestCol)
wkbTemp.Close (False)
iDestCol = iDestCol + 2
Next
Rows("1:20").Delete Shift:=xlUp
ExitHandler:
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
So, I managed to get two macros coded to do what I need. I have one for pulling the data in from selected text files into individual sheets and another to consolidate the sheets into columns of a single sheet. The code for the first macro is here:
Sub TextToSheets()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Name = Dir(FilesToOpen(x))
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
wkbTemp.Sheets(1).Copy
Set wkbAll = ActiveWorkbook
wkbTemp.Close (False)
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=True, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
Range("A19:B19").Select
ActiveCell.FormulaR1C1 = Name
Range("A20").Select
ActiveCell.FormulaR1C1 = "Voltage (V)"
Range("B20").Select
ActiveCell.FormulaR1C1 = "Current (A)"
Rows("1:18").Select
Selection.Delete Shift:=xlUp
x = x + 1
While x <= UBound(FilesToOpen)
Name = Dir(FilesToOpen(x))
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
With wkbAll
wkbTemp.Sheets(1).Move after:=.Sheets(.Sheets.Count)
.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
Range("A19:B19").Select
ActiveCell.FormulaR1C1 = Name
Range("A20").Select
ActiveCell.FormulaR1C1 = "Voltage (V)"
Range("B20").Select
ActiveCell.FormulaR1C1 = "Current (A)"
Rows("1:18").Select
Selection.Delete Shift:=xlUp
End With
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
And for the second here:
Sub CombineSheetsToColumns()
Application.DisplayAlerts = False
On Error Resume Next
Sheets("Summary").Delete
Application.DisplayAlerts = True
n = Application.Worksheets.Count
Sheets.Add.Name = "Summary"
Sheets("Summary").Move after:=Worksheets(Worksheets.Count)
Set MerPos = Range(Cells(1, 2), Cells(1, 3))
Dim sh As Worksheet
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> "Summary" And sh.Name <> Sheets(n + 1).Name Then
Set col = Columns(Columns.Count).End(xlToLeft)
sh.Range("A:A,B:B").Copy Destination:=Sheets("Summary").Range(col, col).Offset(0, 1)
MerPos.Select
Selection.Merge
Set MerPos = Range(MerPos.Offset(0, 1), MerPos.Offset(0, 2))
End If
Next sh
Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Sheets("Summary").Select
Cells.HorizontalAlignment = xlCenter
Columns.AutoFit = xlColumn
End Sub
I added a few lines for adding text and formatting but shouldn't be too hard to get it working for whatever you may need to use it for. Thanks for all the help!
If you want to copy/paste data across a sheet, run the code below.
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("C:\Users\Excel\Desktop\Coding\LinkedIn\Import All Text Files Into One Single Sheet with File Name in Column A\")
' set the starting point to write the data to
'Set cl = ActiveSheet.Cells(1, 1)
Dim sht As Worksheet
Dim LastRow As Long
Set sh = ActiveSheet
' Loop thru all files in the folder
For Each file In folder.Files
' Write file-name
LastRow = sh.Cells(sh.Rows.Count, "A").End(xlUp).Row + 1
Range("A" & LastRow).Select
ActiveCell = file.Name
' open the file
Set txtFile = fso.OpenTextFile(file)
col = 2
Do While Not txtFile.AtEndOfStream
dat = Application.Transpose(Application.Index(Split(txtFile.ReadLine, ","), 1, 0))
sh.Cells(LastRow, col).Resize(UBound(dat), 1) = dat
col = col + 1
Loop
' Clean up
txtFile.Close
'Range(cl.Address).Offset(1, 0).Select
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
If you want to copy/paste data down a sheet, run the code below.
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("C:\Users\Excel\Desktop\Coding\LinkedIn\Import All Text Files Into One Single Sheet with File Name in Column A\")
' set the starting point to write the data to
Set cl = ActiveSheet.Cells(2, 1)
' Loop thru all files in the folder
For Each file In folder.Files
' Write file-name
cl.Value = file.Name
' Open the file
Set FileText = file.OpenAsTextStream(ForReading)
' Read the file one line at a time
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
' Parse the line into | delimited pieces
Items = Split(TextLine, "|")
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, 1 + i).Value = Items(i)
Next
' Move to next row
Set cl = cl.Offset(1, 0)
Loop
' Clean up
FileText.Close
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
I havethe following problem:
To be able to deploy multiple devices, I have edited some VBA code I found here and there and I'm lost at the moment... Because I'm not a coder, and I don't understand exactly what the code does, I can't figure out the solution.
The problem is: when I add 1 device, the .csv file is cluttered with data:
HOSTNAMEHQ,COUNTRYCRE,HARDWARECRE,MAC,UUID,DESCRIPTION,PLATFORM
LPAB00000013293,,,28:F1:0E:30:81:C1,,STOCK,
#N/A,,,#N/A,,STOCK,
#N/A,,,#N/A,,STOCK,
#N/A,,,#N/A,,STOCK,
#N/A,,,#N/A,,STOCK,
#N/A,,,#N/A,,STOCK,
(etc)
When I add 2 or more devices, the .csv file is OK:
HOSTNAMEHQ,COUNTRYCRE,HARDWARECRE,MAC,UUID,DESCRIPTION,PLATFORM
LPAB00000013293,,,28:F1:0E:30:81:C1,,STOCK,
LPAB00000013293,,,28:F1:0E:30:81:C1,,STOCK,
The code I'm using is:
Sub Button_Click()
Call SaveWorksheetsAsCsv
End Sub
Sub SaveWorksheetsAsCsv()
On Error Resume Next
Dim i As Long
Errorknop = vbCritical + vbOKOnly
ThisWorkbook.Sheets("Export").Visible = xlSheetVisible
ThisWorkbook.Sheets("Export").Activate
Range("A1").Select
Selection.End(xlDown).Select
LaRo = ActiveCell.Row
Range("A1").Select
Range("A2").Select
Selection.End(xlDown).Select
LR = ActiveCell.Row
LC = Last(4, ActiveSheet.Cells)
LCR = LC & LR
Range("B1:" & LCR).Copy
ThisWorkbook.Sheets("Export").Visible = xlSheetHidden
ThisWorkbook.Sheets("Export_2").Visible = xlSheetVisible
ThisWorkbook.Sheets("Export_2").Activate
Range("A1").Select
Range("A1").PasteSpecial Paste:=xlPasteValues
Dim LValue As Date
LValue = Now
Dim SaveToDirectory As String
Dim CurrentWorkbook As String
Dim CurrentFormat As Long
Dim strbody As String
Dim SigString As String
Dim Signature As String
CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
SaveToDirectory = "D:\Testmap\Formulieren\"
Worksheets("Export_2").SaveAs Filename:=SaveToDirectory & Day(LValue) & Month(LValue) & Year(LValue) & Hour(LValue) & Minute(LValue) & Second(LValue) & "_1IMPORT_TEMPLATE_NN_AD_SCCM_HP", FileFormat:=xlCSV
ThisWorkbook.Saved = True
Application.Quit
End Sub
Function Last(choice As Integer, rng As Range)
' 1 = last row
' 2 = last column (R1C1)
' 3 = last cell
' 4 = last column (A1)
Dim lrw As Long
Dim lcol As Integer
Select Case choice
Case 1:
On Error Resume Next
Last = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
Case 2:
On Error Resume Next
Last = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
Case 3:
On Error Resume Next
lrw = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
lcol = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
Last = Cells(lrw, lcol).Address(False, False)
If Err.Number > 0 Then
Last = rng.Cells(1).Address(False, False)
Err.Clear
End If
On Error GoTo 0
Case 4:
On Error Resume Next
Last = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
Last = R1C1converter("R1C" & Last, 1)
For i = 1 To Len(Last)
s = Mid(Last, i, 1)
If Not s Like "#" Then s1 = s1 & s
Next i
Last = s1
End Select
End Function
Function GetBoiler(ByVal sFile As String) As String
'Dick Kusleika
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
GetBoiler = ts.readall
ts.Close
End Function
Function R1C1converter(Address As String, Optional R1C1_output As Integer, Optional RefCell As Range) As String
'Converts input address to either A1 or R1C1 style reference relative to RefCell
'If R1C1_output is xlR1C1, then result is R1C1 style reference.
'If R1C1_output is xlA1 (or missing), then return A1 style reference.
'If RefCell is missing, then the address is relative to the active cell
'If there is an error in conversion, the function returns the input Address string
Dim x As Variant
If RefCell Is Nothing Then Set RefCell = ActiveCell
If R1C1_output = xlR1C1 Then
x = Application.ConvertFormula(Address, xlA2, xlR1C1, , RefCell) 'Convert A2 to R1C1
Else
x = Application.ConvertFormula(Address, xlR1C1, xlA2, , RefCell) 'Convert R1C1 to A2
End If
If IsError(x) Then
R1C1converter = Address
Else
'If input address is A1 reference and A1 is requested output, then Application.ConvertFormula
'surrounds the address in single quotes.
If Right(x, 1) = "'" Then
R1C1converter = Mid(x, 2, Len(x) - 2)
Else
x = Application.Substitute(x, "$", "")
R1C1converter = x
End If
End If
End Function
For a coder this might be completely logical or even a big mess, but I really hope someone can give me the solution so the script runs, get's the information for the cells, and then stops when it finds an empty cell. At that moment, write the .csv file and close.
I found the solution using a step-by-step method with F8. Finding the last row was where the error was. Now I'm using:
Cells(Rows.Count, "A").End(xlUp).Row