Overwrite existing data in tabs using macro - excel

I have a found a macro online that read in "dat" file or "text" file and put them in the open excel, creates a tab for every single file that is in the folder designated using the macro below. Now the issue is that I have to keep in re-importing new data in the same excel because data is changing or i just have to re read that file in again.
So this macro always creates a new tab if the name already exist. I need it to overwrite the data and not recreate a new tab. I have other tab that are referencing the imported data tabs. so I am not sure how to do that.
Sub loadMacro()
'UpdatebyExtendoffice6/7/2016
Dim xWb As Workbook
Dim xToBook As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xFiles As New Collection
Dim I As Long
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "C:\Users\"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
xFile = Dir(xStrPath & "*.dat")
If xFile = "" Then
MsgBox "No files found", vbInformation, "Kutools for Excel"
Exit Sub
End If
Do While xFile <> ""
xFiles.Add xFile, xFile
xFile = Dir()
Loop
Set xToBook = ThisWorkbook
If xFiles.Count > 0 Then
For I = 1 To xFiles.Count
Set xWb = Workbooks.Open(xStrPath & xFiles.Item(I))
xWb.Worksheets(1).Copy After:=xToBook.Sheets(xToBook.Sheets.Count)
On Error Resume Next
ActiveSheet.Name = xWb.Name
On Error GoTo 0
xWb.Close False
Next
End If
End Sub

Replace
xWb.Worksheets(1).Copy After:=xToBook.Sheets(xToBook.Sheets.Count)
On Error Resume Next
ActiveSheet.Name = xWb.Name
On Error GoTo 0
with
On Error Resume Next
xToBook.Worksheets(xWb.name).Cells.Clear
With xWb.Worksheets(1).UsedRange
xToBook.Worksheets(xWb.name).Cells(1, 1).Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
On Error GoTo 0

Related

Automatic Import/Graphing of Text Files in Excel

I run a machine which puts out multiple text files which I plot, I have a VBA script which can import all of the files I want to plot from a folder and puts them on their own sheet. I was wondering if there was a way in which I could automatically have them plotted when they are imported as well? I need a separate graph for each pair of tests. That is I have "Test A-1" and "Test A-2" which are plotted against each other, "Test B-1" and "Test B-2" on a new graph etc. Sorry if this is confusing, I am still pretty new to VBA and would love a tool like this to make my life a bit easier. I have included my code which does all the importing below. Each text file (which is just data for a x-y scatter plot) is then given its own sheet, with the data in columns A and B. Apologies in advance for the terrible formatting, I didn't write it!
Sub ImportTextToExcel()
'UpdatebyExtendoffice20180911
Dim xWb As Workbook
Dim xToBook As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xFiles As New Collection
Dim I As Long
Dim xIntRow As Long
Dim xFNum, xFArr As Long
Dim xStrValue As String
Dim xRg As Range
Dim xArr
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
xFile = Dir(xStrPath & "*.txt")
If xFile = "" Then
MsgBox "No files found", vbInformation
Exit Sub
End If
Do While xFile <> ""
xFiles.Add xFile, xFile
xFile = Dir()
Loop
Set xToBook = ThisWorkbook
On Error Resume Next
Application.ScreenUpdating = False
If xFiles.Count > 0 Then
For I = 1 To xFiles.Count
Set xWb = Workbooks.Open(xStrPath & xFiles.Item(I))
xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)
ActiveSheet.Name = xWb.Name
xWb.Close False
xIntRow = ActiveCell.CurrentRegion.Rows.Count
For xFNum = 1 To xIntRow
Set xRg = ActiveSheet.Range("A" & xFNum)
xArr = Split(xRg.Text, " ")
If UBound(xArr) > 0 Then
For xFArr = 0 To UBound(xArr)
If xArr(xFArr) <> "" Then
xRg.Value = xArr(xFArr)
Set xRg = xRg.Offset(ColumnOffset:=1)
End If
Next
End If
Next
Next
End If
Application.ScreenUpdating = True
End Sub
Option Explicit
Sub ImportTextToExcel()
'UpdatebyExtendoffice20180911
Dim xWb As Workbook, xToBook As Workbook, ws As Worksheet
Dim xFile As String, xStrPath As String, xStrValue As String
Dim xRg As Range, cht As Chart
Dim xFiles As New Collection
Dim i As Long
' choose folder
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = "Select a folder"
If .Show = -1 Then
xStrPath = .SelectedItems(1)
End If
End With
If xStrPath = "" Then
Exit Sub
ElseIf Right(xStrPath, 1) <> "\" Then
xStrPath = xStrPath & "\"
End If
' build collection of text files
xFile = Dir(xStrPath & "*.txt")
Do While xFile <> ""
xFiles.Add xFile, xFile
xFile = Dir()
Loop
If xFiles.Count = 0 Then
MsgBox "No files found", vbCritical
Exit Sub
End If
' import data
Set xToBook = ThisWorkbook
Application.ScreenUpdating = False
For i = 1 To xFiles.Count
' import data into new sheet
Set xWb = Workbooks.Open(xStrPath & xFiles.Item(i))
xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)
Set ws = ActiveSheet
ws.Name = xWb.Name
xWb.Close False
' split on space
Set xRg = ws.Range("A1")
xRg.CurrentRegion.TextToColumns Destination:=xRg.Cells(1, 1), _
DataType:=xlDelimited, _
ConsecutiveDelimiter:=True, _
Space:=True, FieldInfo:=Array(Array(1, 1), Array(2, 1))
' create chart
Set cht = ws.Shapes.AddChart.Chart
With cht
.ChartType = xlXYScatter
.SetSourceData Source:=xRg.CurrentRegion
End With
Next
Application.ScreenUpdating = True
MsgBox xFiles.Count & " files imported", vbInformation
End Sub

Importing Files csv from Folder into single sheet

I was using below code to get the multiple CSV files into single sheet.
code is working fine but the issue is that, it should not copy the headers of each file, because each file header is same.
Code should copy the first file header not all files.
One more thing that i do not want first column to copy all sheets name i have tried to remove that filed but code does not work.
Can i get any help.
thanks
Sub CSV()
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder [Kutools for Excel]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = ThisWorkbook.ActiveSheet
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "\" & "*.csv")
Do While xFile <> ""
Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
Columns(1).Insert xlShiftToRight
Columns(1).SpecialCells(xlBlanks).Value = ActiveSheet.Name
ActiveSheet.UsedRange.Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
xWb.Close False
xFile = Dir
Loop
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox "no files csv", , "Kutools for Excel"
End Sub
EDIT: I did two attempts, first one untested, and did it on my phone:
Sub CSV()
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder [Kutools for Excel]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = ThisWorkbook.ActiveSheet
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "\" & "*.csv")
Dim counter as Long
Do While xFile <> ""
Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
Dim sourceRange as Range
Set sourceRange = xWb.Worksheets(1).UsedRange
If counter = 0 then
sourceRange.Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
else
sourceRange.Offset(1, 0).Resize(sourceRange.Rows.Count - 1, sourceRange.Columns.Count).Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
End If
xWb.Close False
xFile = Dir
counter = counter + 1
Loop
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox "no files csv", , "Kutools for Excel"
End Sub
Second attempt from my computer, I refactored the code handled first file case, skipped the clipboard and use proper procedure and variable names.
Public Sub ImportAndAppendCSVFromFolder()
' Set basic error handling
On Error GoTo CleanFail
' Turn off stuff
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
' Prepare and display file dialog to user
Dim customFileDialog As FileDialog
Set customFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
customFileDialog.AllowMultiSelect = False
customFileDialog.Title = "Select a folder"
' Get folder path from file dialog
If customFileDialog.Show = -1 Then
Dim folderPath As String
folderPath = customFileDialog.SelectedItems(1)
End If
' Exit if nothing was selected
If folderPath = vbNullString Then Exit Sub
' Set reference to active sheet (could be replaced to a specific sheet name with this: ThisWorkbook.Worksheets("SheetName") )
Dim targetSheet As Worksheet
Set targetSheet = ThisWorkbook.ActiveSheet
' Get files in directory ending with specific extension
Dim sourceFile As String
sourceFile = Dir(folderPath & "\" & "*.csv")
' Loop through files
Do While sourceFile <> ""
' Open file
Dim sourceWorkbook As Workbook
Set sourceWorkbook = Workbooks.Open(folderPath & "\" & sourceFile)
' Set reference to sheet in file (as it's a csv file, it only has one worksheet)
Dim sourceSheet As Worksheet
Set sourceSheet = sourceWorkbook.Worksheets(1)
' Depending if it's the first file, include headers or not
Dim counter As Long
If counter = 0 Then
' Set reference to used range in source file
Dim sourceRange As Range
Set sourceRange = sourceSheet.UsedRange
' Calc offset if it's first file
Dim rowOffset As Long
rowOffset = 0
Else
' Don't include headers in range
Set sourceRange = sourceSheet.UsedRange.Offset(1, 0).Resize(sourceSheet.UsedRange.Rows.Count - 1, sourceSheet.UsedRange.Columns.Count)
' Calc offset if it's not first file
rowOffset = 1
End If
' Perform copy (as this comes from a csv file, we can skip the clipboard
targetSheet.Range("A" & targetSheet.Rows.Count).End(xlUp).Resize(sourceRange.Rows.Count, sourceRange.Columns.Count).Offset(rowOffset).Value2 = sourceRange.Value2
' Close csv file
sourceWorkbook.Close False
' Get reference to next file
sourceFile = Dir
counter = counter + 1
Loop
CleanExit:
' Turn on stuff again
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Exit Sub
CleanFail:
MsgBox "An error occurred:" & Err.Description
GoTo CleanExit
End Sub

columns repated while combining multiple xml files using macro

I have used the code available online to combine multiple xml files into single excel. It works fine but columns were repeated. Could someone help me in this, how to get rid of duplication while combining the xml files. Please find the code attached.
Sub From_XML_To_XL()
'UpdatebyKutoolsforExcel20151214
Dim xWb As Workbook
Dim xSWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xCount As Long
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder [Kutools for Excel]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Application.ScreenUpdating = False
Set xSWb = ThisWorkbook
xCount = 1
xFile = Dir(xStrPath & "\*.xml")
Do While xFile <> ""
Set xWb = Workbooks.OpenXML(xStrPath & "\" & xFile)
xWb.Sheets(1).UsedRange.Copy xSWb.Sheets(1).Cells(xCount, 1)
xWb.Close False
xCount = xSWb.Sheets(1).UsedRange.Rows.Count + 2
xFile = Dir()
Loop
Application.ScreenUpdating = True
xSWb.Save
Exit Sub
ErrHandler:
MsgBox "no files xml", , "Kutools for Excel"
End Sub

Convertin XML to excel but leading zeroes are getting removed

I am converting XML to excel. I have ID whose values are 00003233 but after conversion to excel it is 3233. I have multiples XML files so I am using code to combine all different XML files. Below is the code.
Sub From_XML_To_XL()
Dim xWb As Workbook
Dim xSWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xCount As Long
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder [Kutools for Excel]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Application.ScreenUpdating = False
Set xSWb = ThisWorkbook
xCount = 1
xFile = Dir(xStrPath & "\*.xml")
Do While xFile <> ""
Set xWb = Workbooks.OpenXML(xStrPath & "\" & xFile)
xWb.Sheets(1).UsedRange.Copy xSWb.Sheets(1).Cells(xCount, 1)
xWb.Close False
xCount = xSWb.Sheets(1).UsedRange.Rows.Count + 2
xFile = Dir()
Loop
Application.ScreenUpdating = True
xSWb.Save
Exit Sub
ErrHandler:
MsgBox "no files xml", , "Error"
End Sub

Macro to select specific columns from multiple csv and importing to one worksheet

I have multiple CSV in one directory, I need to select specific files instead of the entire directory and I want to be able to select the column that I want (X) and import this to a single worksheet!
I have already made the code above but I'm fighting to add a input box that give the capability do select the column that I want to extract from each CSV.
Moreover, whenever I import the CSV there are not sorted correctly. I found out that I need to apply this formula ""=LEFT(F1;1)&TEXT(SUBSTITUTE(F1;LEFT(F1;1);"";"00") " ", but any idea how to apply in code in order to rename the .csv files.
Sub ImportCSVsWithReferenceI()
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xCount As Long
Dim Newname As String
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = ThisWorkbook.ActiveSheet.Add
Newname = InputBox("Name for new worksheet?")
If Newname <> "" Then
Sheets.Add Type:=xlWorksheet
ActiveSheet.Name = Newname
End If
Set xSht = ThisWorkbook.ActiveSheet
If MsgBox("Clear the existing sheet before importing?", vbYesNo, "Kutools for Excel") = vbYes Then
xSht.UsedRange.Clear
xCount = 1
Else
xCount = xSht.Cells(3, Columns.Count).End(xlToLeft).Column + 1
End If
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "\" & "*.csv")
Do While xFile <> ""
Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
Rows(1).Insert xlShiftDown
Range("A1") = ActiveSheet.Name
ActiveSheet.UsedRange.Copy xSht.Cells(1, xCount)
xWb.Close False
xFile = Dir
xCount = xSht.Cells(3, Columns.Count).End(xlToLeft).Column + 1
Loop
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox "error"
End Sub
Data example (some times I want to extract the columns A or B or C or .... :
Example of a result:

Resources