i need code vbs or cmd batch to copy all data from xls, xlsx and txt file in entire folder into one excel file all excel same column size, and text file same column but it separated by tab
Assistant
User
Assistant
User
i need code vbs or cmd batch to copy all data from xls, xlsx and txt file in entire folder in current directory into one excel file all excel same column size, and text file same column but it separated by tab
OPtimze below vbs code:
' Create an Excel application object
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True ' Change to False if you don't want to see the Excel window
Assistant
To achieve the task of copying data from .xls, .xlsx, and .txt files in an entire folder into one Excel file with the same column size, you can use a combination of a VBS script for handling the Excel files and reading the text files. Below is an example of how you can do this using VBScript.
VBScript Example
vbscript
' Define the folder to process
Dim folderPath
folderPath = "C:\path\to\your\folder" ' Change this to your folder path
' Create Excel object
Dim excelApp, workbook, sheet
Set excelApp = CreateObject("Excel.Application")
Set workbook = excelApp.Workbooks.Add()
Set sheet = workbook.Sheets(1)
' Variables for keeping track of row position in Excel
Dim currentRow
currentRow = 1
' Function to import data from Excel files
Sub ImportExcelFiles()
Dim fileSystem, folder, file
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set folder = fileSystem.GetFolder(folderPath)
For Each file In folder.Files
If (LCase(file.Extension) = ".xls" Or LCase(file.Extension) = ".xlsx") Then
Dim srcWorkbook, srcSheet
Set srcWorkbook = excelApp.Workbooks.Open(file.Path)
Set srcSheet = srcWorkbook.Sheets(1)
' Copy data from source sheet
Dim lastRow, lastCol
lastRow = srcSheet.UsedRange.Rows.Count
lastCol = srcSheet.UsedRange.Columns.Count
If lastRow > 0 Then
' Copy the range from source to destination
srcSheet.UsedRange.Copy sheet.Cells(currentRow, 1)
currentRow = currentRow + lastRow
End If
srcWorkbook.Close False
End If
Next
End Sub
' Function to import data from TXT files
Sub ImportTextFiles()
Dim fileSystem, folder, file
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set folder = fileSystem.GetFolder(folderPath)
For Each file In folder.Files
If LCase(file.Extension) = ".txt" Then
Dim txtStream, line
Set txtStream = file.OpenAsTextStream(1) ' 1 = ForReading
Do While Not txtStream.AtEndOfStream
line = txtStream.ReadLine
' Split line by tab and paste into Excel
Dim values
values = Split(line, vbTab)
Dim i
For i = LBound(values) To UBound(values)
sheet.Cells(currentRow, i + 1).Value = Trim(values(i))
Next
currentRow = currentRow + 1
Loop
txtStream.Close
End If
Next
End Sub
' Call the functions to import data
ImportExcelFiles()
ImportTextFiles()
' Format columns to fit the data
sheet.Cells.EntireColumn.AutoFit()
' Save the resulting workbook
Dim savePath
savePath = folderPath & "\CombinedData.xlsx"
workbook.SaveAs savePath
workbook.Close False
excelApp.Quit
' Cleanup
Set sheet = Nothing
Set workbook = Nothing
Set excelApp = Nothing
Set fileSystem = Nothing
WScript.Echo "Data imported successfully to " & savePath
Instructions for Running the Script:
Update Path: Change C:\path\to\your\folder to reflect the folder containing your files.
Save the Script: Copy the above code into a text editor and save it with a .vbs extension (for example, ImportData.vbs).
Run the Script: Double-click the .vbs file to run it. It will create a new Excel file called CombinedData.xlsx in the same folder.
Important Notes:
Ensure that Excel is installed on the machine where you run this script as it automates Excel.
This script processes all .xls, .xlsx, and .txt files in the specified directory.
The script assumes all data starts from the first row in the Excel files and that text files are tab-delimited.
Any errors in accessing files or reading will not be reported in this simple script; consider adding error handling as necessary for production code.
i need code vbs or cmd batch to copy all data from xls, xlsx and txt file in entire folder into one excel file all excel same column size, and text file same column but it separated by tab
but when run below code error:
' Define the folder to process
Dim folderPath
folderPath = "C:\path\to\your\folder" ' Change this to your folder path
' Create Excel object
Dim excelApp, workbook, sheet
Set excelApp = CreateObject("Excel.Application")
Set workbook = excelApp.Workbooks.Add()
Set sheet = workbook.Sheets(1)
' Variables for keeping track of row position in Excel
Dim currentRow
currentRow = 1
' Function to import data from Excel files
Sub ImportExcelFiles()
Dim fileSystem, folder, file
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set folder = fileSystem.GetFolder(folderPath)
code
For Each file In folder.Files
If (LCase(file.Extension) = ".xls" Or LCase(file.Extension) = ".xlsx") Then
Dim srcWorkbook, srcSheet
Set srcWorkbook = excelApp.Workbooks.Open(file.Path)
Set srcSheet = srcWorkbook.Sheets(1)
' Copy data from source sheet
Dim lastRow, lastCol
lastRow = srcSheet.UsedRange.Rows.Count
lastCol = srcSheet.UsedRange.Columns.Count
If lastRow > 0 Then
' Copy the range from source to destination
srcSheet.UsedRange.Copy sheet.Cells(currentRow, 1)
currentRow = currentRow + lastRow
End If
srcWorkbook.Close False
End If
Next
End Sub
' Function to import data from TXT files
Sub ImportTextFiles()
Dim fileSystem, folder, file
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set folder = fileSystem.GetFolder(folderPath)
code
For Each file In folder.Files
If LCase(file.Extension) = ".txt" Then
Dim txtStream, line
Set txtStream = file.OpenAsTextStream(1) ' 1 = ForReading
Do While Not txtStream.AtEndOfStream
line = txtStream.ReadLine
' Split line by tab and paste into Excel
Dim values
values = Split(line, vbTab)
Dim i
For i = LBound(values) To UBound(values)
sheet.Cells(currentRow, i + 1).Value = Trim(values(i))
Next
currentRow = currentRow + 1
Loop
txtStream.Close
End If
Next
End Sub
' Call the functions to import data
ImportExcelFiles()
ImportTextFiles()
' Format columns to fit the data
sheet.Cells.EntireColumn.AutoFit()
' Save the resulting workbook
Dim savePath
savePath = folderPath & "\CombinedData.xlsx"
workbook.SaveAs savePath
workbook.Close False
excelApp.Quit
' Cleanup
Set sheet = Nothing
Set workbook = Nothing
Set excelApp = Nothing
Set fileSystem = Nothing
WScript.Echo "Data imported successfully to " & savePath
Error:
Line: 22
Char: 9
Error: Object doesn't support this property or method: 'file.Extension'
Code: 800A01B6
Source: Microsoft VBScript runtime error
The error you encountered, “Object doesn't support this property or method: 'file.Extension'”, happens because the File object in VBScript does not have an Extension property directly. Instead, you need to access the name of the file and extract the extension from it.
Here's the corrected version of your VBScript, ensuring we check for file extensions correctly:
Corrected VBScript Example
vbscript
' Define the folder to process
Dim folderPath
folderPath = "C:\path\to\your\folder" ' Change this to your folder path
' Create Excel object
Dim excelApp, workbook, sheet
Set excelApp = CreateObject("Excel.Application")
Set workbook = excelApp.Workbooks.Add()
Set sheet = workbook.Sheets(1)
' Variables for keeping track of row position in Excel
Dim currentRow
currentRow = 1
' Function to import data from Excel files
Sub ImportExcelFiles()
Dim fileSystem, folder, file
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set folder = fileSystem.GetFolder(folderPath)
For Each file In folder.Files
If (LCase(file.Name) Like "*.xls" Or LCase(file.Name) Like "*.xlsx") Then
Dim srcWorkbook, srcSheet
Set srcWorkbook = excelApp.Workbooks.Open(file.Path)
Set srcSheet = srcWorkbook.Sheets(1)
' Copy data from source sheet
Dim lastRow
lastRow = srcSheet.UsedRange.Rows.Count
If lastRow > 0 Then
' Copy the range from source to destination
srcSheet.UsedRange.Copy sheet.Cells(currentRow, 1)
currentRow = currentRow + lastRow
End If
srcWorkbook.Close False
End If
Next
End Sub
' Function to import data from TXT files
Sub ImportTextFiles()
Dim fileSystem, folder, file
Set fileSystem = CreateObject("Scripting.FileSystemObject")
Set folder = fileSystem.GetFolder(folderPath)
For Each file In folder.Files
If LCase(file.Name) Like "*.txt" Then
Dim txtStream, line
Set txtStream = file.OpenAsTextStream(1) ' 1 = ForReading
Do While Not txtStream.AtEndOfStream
line = txtStream.ReadLine
' Split line by tab and paste into Excel
Dim values
values = Split(line, vbTab)
Dim i
For i = LBound(values) To UBound(values)
sheet.Cells(currentRow, i + 1).Value = Trim(values(i))
Next
currentRow = currentRow + 1
Loop
txtStream.Close
End If
Next
End Sub
' Call the functions to import data
ImportExcelFiles()
ImportTextFiles()
' Format columns to fit the data
sheet.Cells.EntireColumn.AutoFit()
' Save the resulting workbook
Dim savePath
savePath = folderPath & "\CombinedData.xlsx"
workbook.SaveAs savePath
workbook.Close False
excelApp.Quit
' Cleanup
Set sheet = Nothing
Set workbook = Nothing
Set excelApp = Nothing
Set fileSystem = Nothing
WScript.Echo "Data imported successfully to " & savePath
Key Changes:
File Extension Check: The property file.Extension was changed to use file.Name with a pattern match. I used the Like operator, which is effective for pattern matching in VBScript.
LCase(file.Name) Like "*.xls" checks if the file has an .xls or .xlsx extension.
Maintaining Row Position: The code logic is preserved, and it continues to process the files as you originally intended.
Running the Script:
Make sure to update the folderPath variable to the path where your Excel and TXT files are located.
Save the script with a .vbs extension and double-click to run.
This should work without errors, allowing you to combine data from Excel and TXT files into a single Excel file. If you run into further issues, please share more details, and I'll be glad to help!
' Create a new workbook
Set objWorkbook = objExcel.Workbooks.Add()
Set objSheet = objWorkbook.Worksheets(1)
' Define the row counter for Excel
rowCounter = 1
' Create a FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Get the current directory
currentDir = objFSO.GetAbsolutePathName(".")
' Process .xls and .xlsx files
For Each file In objFSO.GetFolder(currentDir).Files
If LCase(objFSO.GetExtensionName(file.Name)) = "xls" Or LCase(objFSO.GetExtensionName(file.Name)) = "xlsx" Then
Set objSourceWorkbook = objExcel.Workbooks.Open(file.Path)
Set objSourceSheet = objSourceWorkbook.Worksheets(1)
code
' Find the last row in the source sheet
lastRow = objSourceSheet.Cells(objSourceSheet.Rows.Count, 1).End(-4162).Row
' Copy data to the target sheet
For i = 1 To lastRow
objSourceSheet.Rows(i).Copy objSheet.Rows(rowCounter)
rowCounter = rowCounter + 1
Next
objSourceWorkbook.Close False
End If
Next
' Process .txt files
For Each file In objFSO.GetFolder(currentDir).Files
If LCase(objFSO.GetExtensionName(file.Name)) = "txt" Then
Set objTextStream = objFSO.OpenTextFile(file.Path, 1)
code
' Read each line from the text file
Do While Not objTextStream.AtEndOfStream
line = objTextStream.ReadLine
arrValues = Split(line, vbTab) ' Split by tab
' Write to Excel
For col = LBound(arrValues) To UBound(arrValues)
objSheet.Cells(rowCounter, col + 1).Value = arrValues(col)
Next
rowCounter = rowCounter + 1
Loop
objTextStream.Close
End If
Next
' Save the workbook
objWorkbook.SaveAs currentDir & "\CombinedData.xlsx"
objWorkbook.Close
objExcel.Quit
' Cleanup
Set objSheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
Set objFSO = Nothing
Here's an optimized version of your VBScript code for consolidating data from all .xls, .xlsx, and .txt files in the current directory into a single Excel file. I've made several improvements to streamline the code and enhance performance without compromising functionality.
Optimized VBScript Code
vbscript
' Create an Excel application object
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False ' Change to True if you want to see the Excel window
' Create a new workbook and select the first worksheet
Set objWorkbook = objExcel.Workbooks.Add()
Set objSheet = objWorkbook.Worksheets(1)
' Define the row counter to keep track of where to write in Excel
rowCounter = 1
' Create a FileSystemObject to work with files
Set objFSO = CreateObject("Scripting.FileSystemObject")
currentDir = objFSO.GetAbsolutePathName(".") ' Get current directory
' Function to process Excel files
Sub ProcessExcelFiles()
For Each file In objFSO.GetFolder(currentDir).Files
If LCase(objFSO.GetExtensionName(file.Name)) = "xls" Or LCase(objFSO.GetExtensionName(file.Name)) = "xlsx" Then
ProcessExcelFile(file)
End If
Next
End Sub
' Sub to process individual Excel files
Sub ProcessExcelFile(file)
Set objSourceWorkbook = objExcel.Workbooks.Open(file.Path)
Set objSourceSheet = objSourceWorkbook.Worksheets(1)
' Find the last row in the source sheet
lastRow = objSourceSheet.Cells(objSourceSheet.Rows.Count, 1).End(-4162).Row
' Copy data to the target sheet
objSourceSheet.Range("A1:A" & lastRow).EntireRow.Copy objSheet.Rows(rowCounter)
rowCounter = rowCounter + lastRow
objSourceWorkbook.Close False
End Sub
' Function to process text files
Sub ProcessTextFiles()
For Each file In objFSO.GetFolder(currentDir).Files
If LCase(objFSO.GetExtensionName(file.Name)) = "txt" Then
ProcessTextFile(file)
End If
Next
End Sub
' Sub to process individual text files
Sub ProcessTextFile(file)
Set objTextStream = objFSO.OpenTextFile(file.Path, 1) ' For Reading
' Read each line from the text file
Do While Not objTextStream.AtEndOfStream
line = objTextStream.ReadLine
arrValues = Split(line, vbTab) ' Split by tab
' Write to Excel
For col = LBound(arrValues) To UBound(arrValues)
objSheet.Cells(rowCounter, col + 1).Value = Trim(arrValues(col))
Next
rowCounter = rowCounter + 1
Loop
objTextStream.Close
End Sub
' Process the files
ProcessExcelFiles()
ProcessTextFiles()
' Save the workbook
objWorkbook.SaveAs currentDir & "\CombinedData.xlsx"
objWorkbook.Close False
objExcel.Quit
' Cleanup
Set objSheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
Set objFSO = Nothing
WScript.Echo "Data imported successfully into CombinedData.xlsx"
Key Optimizations:
Modularization: Encapsulated the logic to process Excel files and text files into separate subroutines (ProcessExcelFiles, ProcessExcelFile, ProcessTextFiles, and ProcessTextFile). This improves code readability and maintainability.
Batch Copy: Reduced the copying process for Excel files by copying entire rows at once instead of copying row by row within a loop. This minimizes the number of method calls to Excel's object model, improving performance.
Trim Input: Used Trim to clean whitespace from values read from the text file when writing to Excel.
Visibility Control: Set the Excel application visibility to False by default; you can change this if needed.
How to Use:
Ensure you have Excel installed on your machine.
Copy the provided script into a text editor and change the file extension to .vbs (for example, CombineFiles.vbs).
Save the file and double-click it to run. It will create CombinedData.xlsx in the same directory as your script.
This optimized version should perform efficiently and produce the desired output without errors. If you have further questions or need additional functionality, feel free to ask!