I want to copy a specific column from the excel files located in a folder and paste all the values in a new excel sheet.
Completed-
- I am able to loop through all the files located in a folder.
- I am able to copy the data from specific column.
Not able to complete:
- Not able able to paste the copied data.
- I want to copy only the distinct values.
- I want to copy columns till the rows are there. like if there are 7 rows then copy 7 values of column. My copy command is copying all the values up to last row of excel sheet.
My code (VBScipt)-
strPath="C:\Test"
Set objExcel= CreateObject("Excel.Application")
objExcel.Visible= True
Set objExcel2= CreateObject("Excel.Application")
objExcel2.Visible= True
objExcel2.Workbooks.open("C:\Test\New Folder\4.xlsx")
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder (strPath)
For Each objFile In objFolder.Files
If objFso.GetExtensionName(objFile.Path) = "xlsx" Then
objExcel.Workbooks.Open(objFile.Path)
Set Source=objExcel.Activeworkbook.Sheets(1).Columns("G")
Source.Copy
Set dest=objExcel2.Activeworkbook.Sheets(1).Columns("A")
dest.Paste
objExcel.Activeworkbook.save
objExcel.Activeworkbook.close
objExcel2.Activeworkbook.save
objExcel2.Activeworkbook.close
End If
Next
For distinct copying
.AdvancedFilter()
method used, cells defined withgetRange()
from @NickSlash. For data addition from files, new sheet is created for each of them, and then data is filtered to it. I hope this helps.VBScript
I think PasteSpecial will help with the pasting in vb script. It is best to use the -4163 argument in PasteSpecial to ensure that only the values are pasted. The code below worked for me in Microsoft Visual Studio 2012. Added comments just to know where the program is in the code. Hope this helps.
This function will return the used range for a given column on a worksheet.
If you use this in-place of your
Set Source=objExcel.Activeworkbook.Sheets(1).Columns("G")
it should do what you want.eg:
Set Source = getRange("G", objExcel.Activeworkbook.Sheets(1))
You might need to change your
dest
to a cell instead of the column (in-case excel moans about it being the wrong size)Set dest = objExcel.Activeworkbook.Sheets(1).Cells("A1")
Just saw that you tagged it as VBScript, I haven't tested it as VBS but it might work just the same as VBA.