Hyperlinking .mpg files to cells in excel - vb.net

I have a couple of rows of some strings and I'd like to assign them to mpg movies. For example "101 Home Visit 33" need to be linked with 101asd.mpg, the first 3 characters are the same every time. In one catalogue there are over 50 mpg files so I had an idea to make a macro which by using ctrl+h does it automatically (I mean searching and hyper linking). I don't know how to search for a file name. To make it easier I've created second column just with first three characters (101) and its called file_number My code:
Sub Makro1()
'Dim i As Integer
Dim cell_name As String
Dim file_name As String
Dim file_number As String
ActiveCell.Select
cell_name = ActiveCell.Value
ActiveCell.Offset(0, 2).Range("A1").Select
ActiveCell.Select
file_number = ActiveCell.Value
ActiveCell.Offset(0, -2).Range("A1").Select
ActiveCell.Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _
file_number & "*.mpeg", TextToDisplay:= _
file_name
End Sub
Something is wrong with this part:
file_number & "*.mpeg", TextToDisplay:= _
file_name
or to be more precise
"*.mpeg"
because I'm trying to cover some characters with *.
What is wrong?

Along with the other things discussed, you can store the workbook path as a variable to reference if they are all in the same file:
Sub Makro1()
'All Your Other Stuff
Dim strPath As String
strPath = ActiveWorkbook.Path
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _
strPath & "\" & file_number & ".mpeg", TextToDisplay:= _
file_name
'TextToDisplay may be cell_name depending on how you adjusted your code.
End Sub

Problem is solved without using *. I tried in different ways but none of them worked.
Sub Makro1()
For Each cell In Selection
If cell.Value = "" Then
Else
Call linkowanie
End If
ActiveCell.Offset(1, 0).Range("A1").Select 'Jump to lower cell
Next cell
End Sub
Sub linkowanie()
Dim cell_name As String
Dim file_number As String
Dim strPath As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
Dim k As Integer
Dim file_names() As String 'Dynamic array for file names
strPath = ActiveWorkbook.Path 'Path shows way to excel file
ActiveCell.Select
cell_name = ActiveCell.Value
ActiveCell.Offset(0, 2).Range("A1").Select
ActiveCell.Select
file_number = ActiveCell.Value
ActiveCell.Offset(0, -2).Range("A1").Select
ActiveCell.Select
strPath = ActiveWorkbook.Path
Set objFSO = CreateObject("Scripting.FileSystemObject") 'Create an instance of the FileSystemObject
Set objFolder = objFSO.GetFolder(strPath) 'Get the folder object
i = 0
For Each objFile In objFolder.Files
ReDim Preserve file_names(i)
file_names(i) = objFile.Name
i = i + 1
Next objFile
For k = 0 To i - 1
If Mid(file_names(k), 1, 6) = file_number Then
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _
strPath & "\" & file_names(k), TextToDisplay:= _
cell_name
End If
Next k
End Sub

Related

Excel VBA Select worksheets from a list where the value is TRUE

I am attempting to write a macro that will print some sheets to pdf. I have a worksheet ("PDF") that lists all the worksheets in the workbook in column D and next to that in column F I have a list of TRUE/FALSE values. My macro should print all the worksheets in column D that have a TRUE in column F into a single pdf file.
The number of sheets in this workbook does vary.
Below is my first stab at code for this
Sub PDFCreater()
Dim pdfName As String
Dim FullName As String
Dim myArray() As Variant
Dim ArrSize As Integer
Dim ArrWkst As String
Dim RowCnt As Long, ArrCnt As Long
pdfName = Sheets("PDF").Range("D1").Text
FullName = ThisWorkbook.Path & "\" & pdfName & ".pdf"
ReDim myArray(Sheets("PDF").Range("D2").Value) 'Size of array/ number of sheets in PDF
ArrCnt = 0
For RowCnt = 8 To 302
If Sheets("PDF").Cells(RowCnt, 6).Value = True Then
myArray(ArrCnt) = Cells(RowCnt, 4).Value
ArrCnt = ArrCnt + 1
End If
RowCnt = RowCnt + 1
Next
'Select all worksheets in MyArray()
Sheets(myArray).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FullName _
, Quality:=xlQualityMedium, IncludeDocProperties:=False,
IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
According to your description you have several errors in your code
Sub Test()
Dim pdfName As String
Dim FullName As String
Dim myArray() As Variant
Dim ArrSize As Integer
Dim ArrWkst As String
Dim RowCnt As Long, ArrCnt As Long
pdfName = Sheets("PDF").Range("D1").Text
FullName = ThisWorkbook.Path & "\" & pdfName & ".pdf"
' You need to re-dim the array in the loop in order to have an array with
' the correct dimension. Otherwisae the array is too big and will contain
' empty entries
'ReDim myArray(Sheets("PDF").Range("D2").Value) 'Size of array/ number of sheets in PDF
ArrCnt = 0
For RowCnt = 8 To 302
If Sheets("PDF").Cells(RowCnt, 6).Value Then
ReDim Preserve myArray(ArrCnt)
myArray(ArrCnt) = Cells(RowCnt, 4).Value
ArrCnt = ArrCnt + 1
End If
' the for loop will increase rowcnt itself
' no need to do that
'RowCnt = RowCnt + 1
Next
'Select all worksheets in MyArray()
Sheets(myArray).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FullName, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
Use the loop to Hide the Sheets with a FALSE value, then:
ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FullName _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
This will save the whole workbook as PDF with the exception of the hidden sheets.

Merge specific cells from columns from multiple files to one sheet

I am trying to merge data from particular columns from multiple csv files. This thread: Excel VBA - Merge specific columns from multiple files to one sheet worked for whole ranges of columns. However, I want to copy e.g. each 100th cell from particular column (instead of whole column as it is at the moment).
I have tried to modify the code as per below method 1 and 2 (see **** notes).
This VBA is to go through datalog files which have time stamps in rows and parameters for each time stamp. However, I don't want all parameters, only selected ones (per columns) and in each 100th row.
'takes worksheet and returns last row
Private Function LastRowUsed(sh As Worksheet) As Long
On Error Resume Next
LastRowUsed = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
'takes worksheet and returns last column
Private Function LastColUsed(sh As Worksheet) As Long
On Error Resume Next
LastColUsed = sh.Cells.Find(What:="*", _
After:=sh.Range(A1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
End Function
'takes worksheet and returns last row in column
Private Function LastRowUsedbyCol(sh As Worksheet, ByVal Col As String) As Long
On Error Resume Next
LastRowUsed = sh.Cells.Find(What:="*", _
After:=sh.Range(Cell(Col, 1), Cell(Col, 1)), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
Function GetFileListArray() As String()
Dim fileDialogBox As FileDialog
Dim SelectedFolder As Variant
Dim MYPATH As String
Dim MYFILES() As String
Dim FILESINPATH
Dim FNUM, i As Integer
'''''
Set fileDialogBox = Application.FileDialog(msoFileDialogFolderPicker)
'Use a With...End With block to reference the FileDialog object.
With fileDialogBox
If .Show = -1 Then 'the user chose a folder
For Each SelectedFolder In .SelectedItems
MYPATH = SelectedFolder 'asign mypath to the selected folder name
'MsgBox "The path is:" & SelectedFolder, vbInformation 'display folder selected
Next SelectedFolder
'The user pressed Cancel.
Else
MsgBox "Cancel was pressed or Invalid folder chosen, ending macro"
Exit Function
End If
End With
'Set the file dialog object variable to Nothing to clear memory
Set fileDialogBox = Nothing
If Right(MYPATH, 1) <> "\" Then
MYPATH = MYPATH & "\"
End If
FILESINPATH = Dir(MYPATH & "*.csv")
'MsgBox FILESINPATH
If FILESINPATH = "" Then
MsgBox "No files found"
Exit Function
End If
'Fill the array(myFiles)with the list of Excel files in the folder
FNUM = 0
Do While FILESINPATH <> ""
FNUM = FNUM + 1
ReDim Preserve MYFILES(1 To FNUM)
MYFILES(FNUM) = MYPATH & FILESINPATH
FILESINPATH = Dir()
Loop
GetFileListArray = MYFILES()
End Function
Sub RFSSearchThenCombine()
'search first worksheet in files opened, change to search other worksheets
Const SHEET_TO_SEARCH = 1
Dim FileList() As String
Dim CurrentFolder As String
Dim openedWorkBook As Workbook, HeadingWorkbook As Workbook
Dim OpenedWorkSheet As Worksheet, HeadingWorkSheet As Worksheet
Dim i, counter, x, j As Integer
Dim LRowHeading, LRowOpenedBook, LColHeading, LColOpenedBook, LRowHeadingC As Long
Dim dict As dictionary
Dim searchValue
'set original workbook with headings to retrieve
Set HeadingWorkbook = ActiveWorkbook
Set HeadingWorkSheet = HeadingWorkbook.Sheets(1)
'find last column on heading worksheet
LColHeading = LastColUsed(HeadingWorkSheet)
'create dictionary to link headers to position in heading worksheet
Set dict = CreateObject("Scripting.Dictionary")
For x = 1 To LColHeading
dict.Add HeadingWorkSheet.Cells(1, x).Value, x
Next x
FileList() = GetFileListArray()
For counter = 1 To UBound(FileList)
Set openedWorkBook = Workbooks.Open(FileList(counter))
Set OpenedWorkSheet = openedWorkBook.Sheets(SHEET_TO_SEARCH)
LColOpenedBook = LastColUsed(openedWorkBook.Sheets(1))
LRowOpenedBook = LastRowUsed(openedWorkBook.Sheets(1))
LRowHeading = LastRowUsed(HeadingWorkSheet)
For i = 1 To LColOpenedBook 'search headers from a1 to last header
searchValue = OpenedWorkSheet.Cells(1, i).Value 'set search value in to current header
If dict.Exists(searchValue) Then
' *** code from previous thread
'OpenedWorkSheet.Range(OpenedWorkSheet.Cells(1, i), _
'OpenedWorkSheet.Cells(LRowOpenedBook, i)).Copy _
'(HeadingWorkSheet.Cells(LRowHeading, dict.Item(searchValue)))
'**** my proposal
For j = 1 To LRowOpenedBook Step 100
OpenedWorkSheet.Range(OpenedWorkSheet.Cells(j, i), _
OpenedWorkSheet.Cells(j, i)).Copy _
(HeadingWorkSheet.Cells(LRowHeading + 1, dict.Item(searchValue)))
LRowHeading = LRowHeading + 1
'**** my 2nd proposal
'LRowHeadingC = HeadingWorkSheet.Cells(Rows.Count, i).End(xlUp).Row
'For j = 1 To LRowOpenedBook Step 100
' OpenedWorkSheet.Range(OpenedWorkSheet.Cells(j, i), _
'OpenedWorkSheet.Cells(j, i)).Copy _
'(HeadingWorkSheet.Cells(LRowHeadingC + 1, dict.Item(searchValue)))
'LRowHeadingC = LRowHeadingC + 1
Next j
End If
Next i
openedWorkBook.Close (False)
Next counter ' move on to next file
End Sub
1st method (when working) results in shift of rows from next columns (all pasted data start from last row (not last row in particular column), it more less results in below pattern (where cl is for column and x represents data):
cl1 cl2 cl3 cl3
x
x
x
x
x
x
x
x
x x
x
x
x
x
x
While I want to receive below pattern:
cl1 cl2 cl3 cl3
x x x x
x x x x
x x x x
Another question is how should I modify function: LastRowUsed not to start from A1, but e.g. from B1, etc.? I tried to resolve that with Method 2.
Based on feedback above I have changed the loops order and that made it work. I have also polished the code (copying from range to range and added option explicit). Code does the job now.
Now I will be trying to change it to more efficient version (it takes plenty of time with few hundreds of workbooks). At the moment I am copying and pasting each cell individually between workbooks. I think that a set of cells (e.g. multiple selection of each 100th cell) would be quicker.
Or building an array of values needed and pasting array into headingsWorkbook as range.
Here is how the code looks now:
Option Explicit
'takes worksheet and returns last row
Private Function LastRowUsed(sh As Worksheet) As Long
On Error Resume Next
LastRowUsed = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
'takes worksheet and returns last column
Private Function LastColUsed(sh As Worksheet) As Long
On Error Resume Next
LastColUsed = sh.Cells.Find(What:="*", _
After:=sh.Range(A1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
End Function
'takes worksheet and returns last row in column
Private Function LastRowUsedbyCol(sh As Worksheet, ByVal Col As String) As Long
On Error Resume Next
LastRowUsed = sh.Cells.Find(What:="*", _
After:=sh.Range(Cell(Col, 1), Cell(Col, 1)), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
Function GetFileListArray() As String()
Dim fileDialogBox As FileDialog
Dim SelectedFolder As Variant
Dim MYPATH As String
Dim MYFILES() As String
Dim FILESINPATH
Dim FNUM, i As Integer
'''''
Set fileDialogBox = Application.FileDialog(msoFileDialogFolderPicker)
'Use a With...End With block to reference the FileDialog object.
With fileDialogBox
If .Show = -1 Then 'the user chose a folder
For Each SelectedFolder In .SelectedItems
MYPATH = SelectedFolder 'asign mypath to the selected folder name
'MsgBox "The path is:" & SelectedFolder, vbInformation 'display folder selected
Next SelectedFolder
'The user pressed Cancel.
Else
MsgBox "Cancel was pressed or Invalid folder chosen, ending macro"
Exit Function
End If
End With
'Set the file dialog object variable to Nothing to clear memory
Set fileDialogBox = Nothing
If Right(MYPATH, 1) <> "\" Then
MYPATH = MYPATH & "\"
End If
FILESINPATH = Dir(MYPATH & "*.csv")
'MsgBox FILESINPATH
If FILESINPATH = "" Then
MsgBox "No files found"
Exit Function
End If
'Fill the array(myFiles)with the list of Excel files in the folder
FNUM = 0
Do While FILESINPATH <> ""
FNUM = FNUM + 1
ReDim Preserve MYFILES(1 To FNUM)
MYFILES(FNUM) = MYPATH & FILESINPATH
FILESINPATH = Dir()
Loop
GetFileListArray = MYFILES()
End Function
Sub RFSSearchThenCombineEach1000thRow()
'search first worksheet in files opened, change to search other worksheets
Const SHEET_TO_SEARCH = 1
Dim FileList() As String
Dim CurrentFolder As String
Dim openedWorkBook As Workbook, HeadingWorkbook As Workbook
Dim OpenedWorkSheet As Worksheet, HeadingWorkSheet As Worksheet
Dim i, counter, x, j As Integer
Dim LRowHeading, LRowOpenedBook, LColHeading, LColOpenedBook As Long
Dim dict As dictionary
Dim searchValue
'set original workbook with headings to retrieve
Set HeadingWorkbook = ActiveWorkbook
Set HeadingWorkSheet = HeadingWorkbook.Sheets(1)
'find last column on heading worksheet
LColHeading = LastColUsed(HeadingWorkSheet)
'create dictionary to link headers to position in heading worksheet
Set dict = CreateObject("Scripting.Dictionary")
For x = 1 To LColHeading
dict.Add HeadingWorkSheet.Cells(1, x).Value, x
Next x
FileList() = GetFileListArray()
For counter = 1 To UBound(FileList)
Set openedWorkBook = Workbooks.Open(FileList(counter))
Set OpenedWorkSheet = openedWorkBook.Sheets(SHEET_TO_SEARCH)
LColOpenedBook = LastColUsed(openedWorkBook.Sheets(1))
LRowOpenedBook = LastRowUsed(openedWorkBook.Sheets(1))
LRowHeading = LastRowUsed(HeadingWorkSheet)
For j = 2 To LRowOpenedBook Step 1000
LRowHeading = LRowHeading + 1 'move one row down in HeadingWorkbook, each 1000 rows of openedworkbook
For i = 1 To LColOpenedBook 'search headers from a1 to last header
searchValue = OpenedWorkSheet.Cells(1, i).Value 'set search value in to current header
If dict.Exists(searchValue) Then
OpenedWorkSheet.Range(OpenedWorkSheet.Cells(j, i), _
OpenedWorkSheet.Cells(j, i)).Copy _
HeadingWorkSheet.Range(HeadingWorkSheet.Cells(LRowHeading, dict.Item(searchValue)), _
HeadingWorkSheet.Cells(LRowHeading, dict.Item(searchValue)))
End If
Next i
Next j
openedWorkBook.Close (False)
Next ' move on to next file
End Sub

Compare two workbooks using VBA

I was trying to compare two different Workbooks, one named "after" (which is up to date) and another called "before" and I wanted to highlight the differences so it would be easy to pin down what changed between the two.
Okay so after I tested it a bit I got stuck in an error
"Object doesn't support this property or method".
Here's the full code with added comments so you can follow my thought process:
Sub OpenCsv()
Dim zcf, FolderPath, after, before, shtAfter, shtBefore As String
Dim MotherWB As Workbook, MotherWS As Worksheet
Dim wb As Workbook, ws, worksheetz As Worksheet
Dim oneRange, aCell As Range
Dim rng As Range
Dim Answer As Integer
Dim mycell As Range
Dim mydiffs As Integer
'Sorts Things for MotherWB
Set oneRange = Range("A4:Z9000")
Set aCell = Range("F4")
oneRange.Sort Key1:=aCell, Order1:=xlAscending, Header:=xlYes
'Opens and sets both Workbooks with their respective sheets
FolderPath = Application.ActiveWorkbook.Path
after = FolderPath + "\" + "after.csv"
before = FolderPath + "\" + "before.xlsm"
Workbooks.Open (after)
Set wb = Workbooks("after.csv")
Set ws = wb.Worksheets("after")
Set MotherWB = Workbooks("before.xlsm")
Set MotherWS = MotherWB.Worksheets("before")
'Makes ws looks like MotherWS so we compare them
With ws
Columns("A:Z").AutoFit
Selection.TextToColumns _
Destination:=Range("A1:A9000"), _
DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=True, _
Space:=False, _
Other:=False
Set oneRange = Range("A4:Z9000")
Set aCell = Range("F4")
oneRange.Sort Key1:=aCell, Order1:=xlAscending, Header:=xlYes
End With
'Questions if you want to compare both
Answer = MsgBox("Uma vez aberto o relatório deseja comparar os dois?", vbYesNo + vbQuestion, "Comparar")
If Answer = 6 Then
'For each cell in after that is not the same in before, color it yellow
For Each mycell In wb.ws(after).UsedRange
If Not mycell.Value = MotherWB.MotherWS(before).Cells(mycell.row, mycell.Column).Value Then
mycell.Interior.Color = vbYellow
mydiffs = mydiffs + 1
End If
Next
'Display a message box to demonstrate the differences
MsgBox mydiffs & " differences found", vbInformation
ActiveWorkbook.Sheets(after).Select
End If
End Sub
It gets the error after I return 6 from the answer, saying what I stated above. What am I doing wrong?
Answer is set as boolean and the msgbox will return a integer. Declare an integer and then use an if statement to put true/false in your answer variable. Something similar to below
Dim temp as integer
temp = MsgBox("Uma vez aberto o relatório deseja comparar os dois?", vbYesNo + vbQuestion, "Comparar")
if temp = 6 then
Answer = true
else
Answer = false
endif

Merge Files in order

I have the below vba macro for merging multiple files. However, when im merging the files, they dont merge in order of how my folder is set up for that path. Could someone tell me how i could get my files to merge in order?
Dim booklist As Workbook
Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object
Application.ScreenUpdating = False
Set mergeObj = CreateObject("Scripting.FileSystemObject")
Set dirObj = mergeObj.Getfolder("PATH")
Set filesObj = dirObj.Files
For Each everyObj In filesObj
Set booklist = Workbooks.Open(everyObj)
Range("A1:H27").Copy
ThisWorkbook.Worksheets(1).Activate
Range("A65536").End(xlUp).Offset(2, 0).PasteSpecial
Application.CutCopyMode = False
booklist.Close
Next
Rows("1:1").Select
Selection.Delete Shift:=xlUp
Rows("1:1").Select
Selection.Delete Shift:=xlUp
Range("A1").Select
End Sub
The files will always appear in a random order in your VBA code. In order to set your own sort order, you can define it using the .Folder and it's properties. Look at the documentation for the MSDN - Folder Object and then the Items.Sort Method.
Alternatively, you can read in all the file names and sort them in your VBA-based array as discussed over in CodingHorror.
My solution is for the case when is need to merge excel files into one file in these files creation order.
Sub Main()
Dim sourceWorkbook As Workbook
Dim FSO As Object
Dim sourceFolder As Object
Dim file As Object
Dim templatePath As String, templateName As String, sourceFolderPath As String
Dim destinationFileNamePrefix As String, destinationFolderPath As String
Dim moveMergedFilesToBackup As Boolean, backupUpperFolderPath As String
Dim lastTemplateColumn As Integer, fullyFilledColumnNumber As Integer, lastSourceFileColumn As Integer, sourceFileName As String
Dim lastRow As Long, i As Long, insertExecutionNumber As Boolean, executionNumber As Long
Dim sortingWorkbook As Workbook, rowNo As Long, lastArrayIndex As Long, sourceFilesPathArray() As String
Application.ScreenUpdating = False
Call LoadSettings.LoadDataFromControlSheet(templatePath, sourceFolderPath, fullyFilledColumnNumber, destinationFolderPath, _
destinationFileNamePrefix, moveMergedFilesToBackup, backupUpperFolderPath, insertExecutionNumber)
Workbooks.Open fileName:=templatePath
templateName = Right(templatePath, Len(templatePath) - InStrRev(templatePath, "\"))
Workbooks(templateName).Activate
Call SaveFiles.SaveTemplateToTemporaryFolder(templateName)
lastTemplateColumn = Range("A1").End(xlToRight).Column
Set FSO = CreateObject("Scripting.FileSystemObject")
Set sourceFolder = FSO.Getfolder(sourceFolderPath)
'Create a new workbook for files sorting in ascending order according their creation date
Set sortingWorkbook = Workbooks.Add
'sortingWorkbook.Name = "SortingWorkbook.xlsx"
'Call SaveFiles.SaveTemplateToTemporaryFolder(sortingWorkbook.Name)
sortingWorkbook.Activate
Range("A1") = "File path"
Range("B1") = "Creation Date and Time"
'Write required data into sorting workbook
rowNo = 2
For Each file In sourceFolder.Files
sourceFileName = file.Name
If InStr(sourceFileName, ".xlsx") Then ' Only xlsx files will be merged
Range("A" & rowNo) = file.Path
Range("B" & rowNo) = file.DateCreated
rowNo = rowNo + 1
End If ' If InStr(sourceFileName, ".xlsx") Then' Only xlsx files will be merged
Next
'Sort by file creation date and time - column B
Range("A1:B1").Select
Selection.AutoFilter
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Add Key:=Range _
("B1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Read filepath into array
lastArrayIndex = rowNo - 3 ' rowNo at this moment is +1 than rows, data is from 2 row, array is 0 Based, so -3
ReDim sourceFilesPathArray(lastArrayIndex) 'size array
rowNo = 2
For i = 0 To lastArrayIndex
sourceFilesPathArray(i) = Range("A" & rowNo)
rowNo = rowNo + 1
Next i
sortingWorkbook.Close saveChanges:=False
'Open source files and merge them into accumulation template
For i = 0 To lastArrayIndex
Set sourceWorkbook = Workbooks.Open(sourceFilesPathArray(i))
'Check if source file headers columns number corresponds template to which will be merged data columns number
lastSourceFileColumn = Range("A1").End(xlToRight).Column
If lastSourceFileColumn = lastTemplateColumn Then
lastRow = Cells(Rows.Count, fullyFilledColumnNumber).End(xlUp).Row
Range(Cells(2, 1), Cells(lastRow, lastSourceFileColumn)).Copy
Workbooks(templateName).Activate
lastRow = Cells(Rows.Count, fullyFilledColumnNumber).End(xlUp).Row
Range("A" & lastRow + 1).PasteSpecial
Application.CutCopyMode = False
sourceWorkbook.Close
Else
MsgBox "In the source directory was found xlsx format file" & vbNewLine & _
sourceFilesPathArray(i) & vbNewLine & _
"which has data columns number " & lastSourceFileColumn & vbNewLine & _
"which is different from template into which data are accumulated " & vbNewLine & _
"data columns number " & lastTemplateColumn & "." & vbNewLine & _
"This program will end now." & vbNewLine & _
"Check if you selected correct template and source folder or" & vbNewLine & _
"remove incorrect source file from source folder and then" & vbNewLine & _
"restart the program", vbCritical, ThisWorkbook.Name
Workbooks(templateName).Close saveChanges:=False
sourceWorkbook.Close
End
End If
Next i
Set sourceWorkbook = Nothing
Set filesObj = Nothing
Set FSO = Nothing
'Save accumulated in template data into destination folder with name formed by settings
Call SaveFiles.SaveMergedDataIntoDestination(templateName, destinationFileNamePrefix, destinationFolderPath)
Application.ScreenUpdating = True
End Sub

Copy data from one workbook to new workbook in excel VB

I want to copy selected columns of a file from a worksheet to a new workbook using VBS in Excel. The following code gives the empty columns in new file.
Option Explicit
'Function to check if worksheets entered in input boxes exist
Public Function wsExists(ByVal WorksheetName As String) As Boolean
On Error Resume Next
wsExists = (Sheets(WorksheetName).Name <> "")
On Error GoTo 0 ' now it will error on further errors
End Function
Sub createEndUserWB()
Dim i As Integer
Dim colFound As String
Dim b(1 To 1) As Integer
Dim Sheet_Copy_From As String
Dim newSheet As String
Dim colVal As Variant 'sheet name from array to test
Dim colNames As Variant 'Array
Dim col As Variant
Dim colN As Integer
Dim lkr As Range
Dim destWS As Worksheet
Dim endUserWB As Workbook
Dim lastRow As Integer
'Application.ScreenUpdating = False 'Speeds up the routine by not updating the screen.
'IMPORTANT, remember to turn screen updating back on before the routine ends
'***** ENTERING WORKSHEET NAMES *****
'Get the name of the worksheet to be copied from
Sheet_Copy_From = Application.InputBox(Prompt:= _
"Please enter the sheet name you which to copy from", _
Title:="Sheet_Copy_From", Type:=2) 'Type:=2 = text
If Sheet_Copy_From = "False" Then 'If Cancel is clicked on Input Box exit sub
Exit Sub
End If
'*****CHECK TO SEE IF WORKSHEETS EXIST (USES FUNCTION AT VERY TOP)*****
Select Case wsExists(Sheet_Copy_From) 'calling function at very top
Case False
MsgBox "The worksheet named """ & Sheet_Copy_From & """ is either missing" & vbNewLine & _
"or spelt incorrectly" & vbNewLine & vbNewLine & _
"Please rectify and then run this procedure again" & vbNewLine & vbNewLine & _
"Select OK to exit", _
vbInformation, ""
Exit Sub
End Select
Set destWS = ActiveWorkbook.Sheets(Sheet_Copy_From)
'array of sheet names to test for
colNames = Array("SID", "First Name", "Last Name", "xyz", "Telephone Number", "Department")
'Get the name of the worksheet to pasted into
newSheet = Application.InputBox(Prompt:= _
"Please enter the sheet name you which to paste in", _
Title:="New File", Type:=2) 'Type:=2 = text
If newSheet = "False" Then 'If Cancel is clicked on Input Box exit sub
Exit Sub
End If
Set endUserWB = Workbooks.Add
endUserWB.SaveAs Filename:=newSheet
endUserWB.Sheets(1).Name = "Sheet1"
'endUserWS.Name = "End User"
'Copy Columns 1 by 1
i = 1
For Each col In colNames
On Error GoTo colNotFound
colN = destWS.Rows(1).Find(col, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False).Column
lastRow = destWS.Cells(Rows.Count, colN).End(xlUp).Row
'MsgBox "Column for " & colN & " is " & lastRow, vbInformation, ""
'Copy paste Part begins here
If colN <> -1 Then
'destWS.Select
'colVal = destWS.Columns(colN).Select
'Selection.Copy
'endUserWB.ActiveSheet.Columns(i).Select
'endUserWB.ActiveSheet.PasteSpecial Paste:=xlPasteValues
'endUserWB.Sheets(1).Range(Cells(2, i), Cells(lastRow, i)).Value = destWS.Range(Cells(2, colN), Cells(lastRow, colN))
destWS.Range(2, lastRow).Copy
endUserWB.Worksheets("Sheet1").Range(2).PasteSpecial (xlPasteValues)
End If
i = i + 1
Next col
Application.CutCopyMode = False 'Clears the clipboard
'MsgBox "Column """ & colN & """ is Found",vbInformation , ""
colNotFound:
colN = -1
Resume Next
End Sub
What is wrong with code? Any other method to copy? I followed the answer at Copy from one workbook and paste into another as well. But it also gives blank sheet.
If I understood it right try changing this part of your code:
destWS.Range(2, lastRow).Copy
endUserWB.Worksheets("Sheet1").Range(2).PasteSpecial (xlPasteValues)
by:
destWS.Activate
destWS.Range(Cells(2, colN), Cells(lastRow, colN)).Copy
endUserWB.Activate
endUserWB.Worksheets("Sheet1").Cells(2, colN).PasteSpecial (xlPasteValues)