Merge Files in order - vba

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

Related

Is there a way to export and Excel sheet without copying to a workbook?

I have a workbook that can export the working sheet to a .csv but it copies it into a new workbook for a second before saving im wondering if there is a way just to copy data from the sheet as is without opening a new workbook ? the code i have is:
Sub CopyToCSV()
Dim FlSv As Variant
Dim MyFile As String
Dim sh As Worksheet
Dim MyFileName As String
Dim DateString As String
Application.ScreenUpdating = False
DateString = Format(Now(), "dd-mm-yyyy_hh-mm-ss-AM/PM") '<~~ uses current time from computer clock down to the second
MyFileName = "Results - " & DateString
Set sh = Sheets("Sheet1")
sh.Copy
FlSv = Application.GetSaveAsFilename(MyFileName, fileFilter:="CSV (Comma delimited) (*.csv), *.csv", Title:="Where should we save this?")
If FlSv = False Then GoTo UserCancel Else GoTo UserOK
UserCancel: '<~~ this code is run if the user cancels out the file save dialog
ActiveWorkbook.Close (False)
MsgBox "Export Canceled"
Exit Sub
UserOK: '<~~ this code is run if user proceeds with saving the file (clicks the OK button)
MyFile = FlSv
With ActiveWorkbook
.SaveAs (MyFile), FileFormat:=xlCSV, CreateBackup:=False
.Close False
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Try this (tested on a simple dataset)
Private Sub ExportToCsv()
Dim ws As Worksheet
Dim delim As String, LastCol As String, csvFile As String, CsvLine As String
Dim aCell As Range, DataRange As Range
Dim ff As Long, lRow As Long, lCol As Long
Dim i As Long, j As Long
'~~> We use "," as delimiter
delim = ","
'~~> Change this to specify your file name and path
csvFile = "C:\Users\Siddharth\Desktop\Sample.Csv"
'~~> Change this to the sheet which you want to export as csv
Set ws = ThisWorkbook.Sheets("Sheet9")
With ws
'~~> Find last row and last column
lRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
lCol = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
'~~> Column number to column letter
LastCol = Split(Cells(, lCol).Address, "$")(1)
'~~> This is the range which will be exported
Set DataRange = .Range("A1:" & LastCol & lCol)
'
'~~> Loop through cells in the range and write to text file
'
ff = FreeFile
Open csvFile For Output As #ff
For i = 1 To lRow
For j = 1 To lCol
CsvLine = CsvLine & (delim & Replace(.Cells(i, j).Value, """", """"""""))
Next j
Print #ff, Mid(CsvLine, 2)
CsvLine = ""
Next
'~~> Close text file
Close #ff
End With
End Sub
Sub CopyToCSV()
Dim FlSv As Variant
Dim MyFile As String
Dim sh As Worksheet
Dim MyFileName As String
Dim strTxt As String
Dim vDB, vR() As String, vTxt()
Dim i As Long, n As Long, j As Integer
Dim objStream
Dim strFile As String
Application.ScreenUpdating = False
DateString = Format(Now(), "dd-mm-yyyy_hh-mm-ss-AM/PM") '<~~ uses current time from computer clock down to the second
MyFileName = "Results - " & DateString
FlSv = Application.GetSaveAsFilename(MyFileName, fileFilter:="CSV (Comma delimited) (*.csv), *.csv", Title:="Where should we save this?")
If FlSv = False Then GoTo UserCancel Else GoTo UserOK
UserCancel: '<~~ this code is run if the user cancels out the file save dialog
ActiveWorkbook.Close (False)
MsgBox "Export Canceled"
Exit Sub
UserOK: '<~~ this code is run if user proceeds with saving the file (clicks the OK button)
Set objStream = CreateObject("ADODB.Stream")
MyFile = FlSv
vDB = ActiveSheet.UsedRange
For i = 1 To UBound(vDB, 1)
n = n + 1
ReDim vR(1 To UBound(vDB, 2))
For j = 1 To UBound(vDB, 2)
vR(j) = vDB(i, j)
Next j
ReDim Preserve vTxt(1 To n)
vTxt(n) = Join(vR, ",")
Next i
strtxt = Join(vTxt, vbCrLf)
With objStream
.Charset = "utf-8"
.Open
.WriteText strtxt
.SaveToFile FlSv, 2
.Close
End With
Set objStream = Nothing
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Copy one worksheet to multiple workbooks and remove external references

I am trying to copy one worksheet All Data to around 140 other workbooks. None of the other workbooks have a worksheet with the same name.
The code I am using is below
Sub DataAllSheet()
Dim path As String
Dim file As String
Dim wkbk As Workbook
Dim rCell As Range
Application.ScreenUpdating = False
Application.DisplayAlerts = False
path = "I:test\"
file = Dir(path)
Application.DisplayAlerts = False
Do While Not file = ""
Workbooks.Open (path & file)
Set wkbk = ActiveWorkbook
Sheets.Add After:=Sheets(Sheets.Count)
On Error GoTo Sheet_exists
ActiveSheet.Name = "All Data"
On Error GoTo 0
ThisWorkbook.Sheets("All Data").Range("A2:DH2").Copy Destination:=wkbk.Sheets("All Data").Range("A2")
For Each rCell In wkbk.Sheet("All Data").UsedRange
If InStr(rCell.Formula, ThisWorkbook.Name) > 0 Then
rCell.Replace what:="[*]", replacement:=""
End If
Next
wkbk.Save
wkbk.Close
file = Dir
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
Sheet_exists:
Sheets("All Data").Delete
Resume
End Sub
When I click run I get a Run-Time error 424 Object Required. When I click debug it highlights-
For Each rCell In wkbk.Sheet("All Data").UsedRange
I am not sure what object is required?
I have just realized that some of the other workbooks in the I:test\ folder are saved as .xlsx would this cause the error?
Replace the entire for-next loop with:
wkbk.Worksheets("All Data").UsedRange.Value = wkbk.Worksheets("All Data").UsedRange.Value
What, exactly, are you trying to do? Are you copying unique values in a column to different workbooks? If so, run the script below. This will do that thing.
The range for the code example below looks like this
Column A : Header in A1 = Country, A2:A? = Country names
Column B : Header in B1 = Name, B2:B? = Names
Column C : Header in C1 = Gender, C2:C? = F or M
Column D : Header in D1 = Birthday, D2:D? = Dates
This example will create a new folder for you with a new workbook for every unique value in the first column of the range.The workbooks will be saved with the Unique value in the name into the newly created folder. It will also add a worksheet to your workbook named "RDBLogSheet" with hyperlinks to the newly created workbooks so it is easy to open the workbooks. Every time you run the macro it delete this worksheet first so the information is up to date.
Check if the information in these lines in the macro is correct before you run the macro
1: Set filter range on ActiveSheet: A1 is the top left cell of your filter range and the header of the first column, D is the last column in the filter range. You can also add the sheet name to the code like this :
Worksheets("Sheet1").Range("A1:D" & LastRow(Worksheets("Sheet1")))
No need that the sheet is active then when you run the macro when you use this.
Set My_Range = Range("A1:D" & LastRow(ActiveSheet))
2: Set the Filter field:This example filter on the first column in the range (change the field if needed). In this case the range starts in A so Field 1 is
column A, 2 = column B, ......
FieldNum = 1
3:Important:This macro call a function named LastRow
You find this function below the macro, copy this function together with the macro in a standard module
Sub Copy_To_Workbooks()
'Note: This macro use the function LastRow
Dim My_Range As Range
Dim FieldNum As Long
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim CalcMode As Long
Dim ViewMode As Long
Dim ws2 As Worksheet
Dim MyPath As String
Dim foldername As String
Dim Lrow As Long
Dim cell As Range
Dim CCount As Long
Dim WSNew As Worksheet
Dim ErrNum As Long
'Set filter range on ActiveSheet: A1 is the top left cell of your filter range
'and the header of the first column, D is the last column in the filter range.
'You can also add the sheet name to the code like this :
'Worksheets("Sheet1").Range("A1:D" & LastRow(Worksheets("Sheet1")))
'No need that the sheet is active then when you run the macro when you use this.
Set My_Range = Range("A1:D" & LastRow(ActiveSheet))
My_Range.Parent.Select
If ActiveWorkbook.ProtectStructure = True Or _
My_Range.Parent.ProtectContents = True Then
MsgBox "Sorry, not working when the workbook or worksheet is protected", _
vbOKOnly, "Copy to new workbook"
Exit Sub
End If
'This example filters on the first column in the range(change the field if needed)
'In this case the range starts in A so Field:=1 is column A, 2 = column B, ......
FieldNum = 1
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
'Set the file extension/format
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2013
If ActiveWorkbook.FileFormat = 56 Then
FileExtStr = ".xls": FileFormatNum = 56
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
End If
'Change ScreenUpdating, Calculation, EnableEvents, ....
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
ActiveSheet.DisplayPageBreaks = False
'Delete the sheet RDBLogSheet if it exists
On Error Resume Next
Application.DisplayAlerts = False
Sheets("RDBLogSheet").Delete
Application.DisplayAlerts = True
On Error GoTo 0
' Add worksheet to copy/Paste the unique list
Set ws2 = Worksheets.Add(After:=Sheets(Sheets.Count))
ws2.Name = "RDBLogSheet"
'Fill in the path\folder where you want the new folder with the files
'you can use also this "C:\Users\Ron\test"
MyPath = Application.DefaultFilePath
'Add a slash at the end if the user forget it
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
'Create folder for the new files
foldername = MyPath & Format(Now, "yyyy-mm-dd hh-mm-ss") & "\"
MkDir foldername
With ws2
'first we copy the Unique data from the filter field to ws2
My_Range.Columns(FieldNum).AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=.Range("A3"), Unique:=True
'loop through the unique list in ws2 and filter/copy to a new sheet
Lrow = .Cells(Rows.Count, "A").End(xlUp).Row
For Each cell In .Range("A4:A" & Lrow)
'Filter the range
My_Range.AutoFilter Field:=FieldNum, Criteria1:="=" & _
Replace(Replace(Replace(cell.Value, "~", "~~"), "*", "~*"), "?", "~?")
'Check if there are no more then 8192 areas(limit of areas)
CCount = 0
On Error Resume Next
CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible) _
.Areas(1).Cells.Count
On Error GoTo 0
If CCount = 0 Then
MsgBox "There are more than 8192 areas for the value : " & cell.Value _
& vbNewLine & "It is not possible to copy the visible data." _
& vbNewLine & "Tip: Sort your data before you use this macro.", _
vbOKOnly, "Split in worksheets"
Else
'Add new workbook with one sheet
Set WSNew = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
'Copy/paste the visible data to the new workbook
My_Range.SpecialCells(xlCellTypeVisible).Copy
With WSNew.Range("A1")
' Paste:=8 will copy the columnwidth in Excel 2000 and higher
' Remove this line if you use Excel 97
.PasteSpecial Paste:=8
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
.Select
End With
'Save the file in the new folder and close it
On Error Resume Next
WSNew.Parent.SaveAs foldername & _
cell.Value & FileExtStr, FileFormatNum
If Err.Number > 0 Then
Err.Clear
ErrNum = ErrNum + 1
WSNew.Parent.SaveAs foldername & _
"Error_" & Format(ErrNum, "0000") & FileExtStr, FileFormatNum
.Cells(cell.Row, "B").Formula = "=Hyperlink(""" & foldername & _
"Error_" & Format(ErrNum, "0000") & FileExtStr & """)"
.Cells(cell.Row, "A").Interior.Color = vbRed
Else
.Cells(cell.Row, "B").Formula = _
"=Hyperlink(""" & foldername & cell.Value & FileExtStr & """)"
End If
WSNew.Parent.Close False
On Error GoTo 0
End If
'Show all the data in the range
My_Range.AutoFilter Field:=FieldNum
Next cell
.Cells(1, "A").Value = "Red cell: can't use the Unique name as file name"
.Cells(1, "B").Value = "Created Files (Click on the link to open a file)"
.Cells(3, "A").Value = "Unique Values"
.Cells(3, "B").Value = "Full Path and File name"
.Cells(3, "A").Font.Bold = True
.Cells(3, "B").Font.Bold = True
.Columns("A:B").AutoFit
End With
'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False
If ErrNum > 0 Then
MsgBox "Rename every WorkSheet name that start with ""Error_"" manually" _
& vbNewLine & "There are characters in the name that are not allowed" _
& vbNewLine & "in a sheet name or the worksheet already exist."
End If
'Restore ScreenUpdating, Calculation, EnableEvents, ....
My_Range.Parent.Select
ActiveWindow.View = ViewMode
ws2.Select
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlValues, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
http://www.rondebruin.nl/win/s3/win006_3.htm

Space check previous page and insert rows there Excel

I have block of text in (A795:O830). It is separated from other pages by Page Break and is always the last page of printed (xls, pdf) document. Sometimes there are a lot of free space on first pages and (A795:O830) could have fitted there. Now it is done by Page Break and is not changeble. In my situation 66 rows can fit on one page.
Is there any macro that can automatically check if there is enough empty space on previous page to fit (A795:O830) and insert it there?
Here is my current macro:
Sub Remove_color()
Dim myRange As Range
Dim cell As Range
Set myRange = Range("A24:O785")
For Each cell In myRange
myRange.Interior.ColorIndex = 0
Next
End Sub
Sub Hide_empty_cells()
Set rr = Range("A24:N832")
For Each cell In rr
cell.Select
If cell.HasFormula = True And cell.Value = "" And cell.EntireRow.Hidden = False Then Rows(cell.Row).EntireRow.Hidden = True
Next cell
End Sub
Sub Save_excel()
Dim iFileName$, iRow&, iCol&, iCell As Range, iArr
iFileName = ThisWorkbook.Path & "\New_folder_" & [D5] & "_" & ".xls"
iArr = Array(1, 3, 4): iCol = UBound(iArr) + 1
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlManual
ThisWorkbook.Sheets(2).Copy
With ActiveWorkbook.ActiveSheet
.Buttons.Delete '.Shapes("Button 1").Delete
.UsedRange.Value = .UsedRange.Value
.SaveAs iFileName, xlExcel8: .Parent.Close
End With
Application.Calculation = xlAutomatic
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Sub Save_pdf()
ActiveWorkbook.Sheets(2).Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\New_folder_\" & [D5] & "_" & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=No, _
OpenAfterPublish:=False
End Sub
Sub doitallplease()
Call Remove_color
Call Hide_empty_cells
Call Save_excel
Call Save_pdf
End Sub

Export sheet as CSV, add new column with header and insert workbook name in all the cells

I want to create a macro that copies a sheet called "Week" from my workbook, deletes the first row, adds a new column (farthest to the left), assigns it the header "Department" and assigns it a fixed value. The fixed value should be the name of the CSV file. The name can be found on the front page in cell G6. I don't want the fixed value to be copied all the way down in the first column. I want it to be copied until there isn't any value in any of the columns to the right of the first column. Currently I've tried just comparing it to the second column (column B). I get the message:
Run-time error '424':
Object required
and is referring back to:ยจ
If InStr(1, thiswork.Sheets(ActiveSheet.Name).Range("$B$" & X), "") > 0 Then
This is my code:
Sub Export_pb_uge()
Dim MyPath As String
Dim MyFileName As String
MyPath = "C:mypath1"
MyFileName = Sheets("Front_Page").Range("g6").Value
Application.ScreenUpdating = False
Application.DisplayAlerts = False
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Sheets("PB_uge").Visible = True
Sheets("PB_uge").Copy
Rows(1).EntireRow.Delete
With target_sheet
Range("A1").EntireColumn.Insert
Range("A1").Value = "Department"
End With
If ThisWorkbook.Sheets(ActiveSheet.Name).FilterMode Then ThisWorkbook.Sheets(ActiveSheet.Name).ShowAllData
lRow = ThisWorkbook.Sheets(ActiveSheet.Name).Cells(Rows.Count, "B").End(xlUp).Row
For X = 1 To lRow
If InStr(1, thiswork.Sheets(ActiveSheet.Name).Range("$B$" & X), "") > 0 Then
target_sheet.Range("$A$" & X) = ActiveSheet.Name
End If
Next
With ActiveWorkbook
.SaveAs Filename:= _
MyPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False, _
Local:=True
.Close False
End With
Sheets("Week").Visible = False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Well spotted gazzz0x2z, however I would also declare and set target_sheet
Dim target_sheet As Worksheet
Set target_sheet = ActiveSheet ' or for example Sheets("sheet1")
With target_sheet
Range("A1").EntireColumn.Insert
Range("A1").Value = "Department"
End With
If ThisWorkbook.Sheets(ActiveSheet.Name).FilterMode Then ThisWorkbook.Sheets (ActiveSheet.Name).ShowAllData
lRow = ThisWorkbook.Sheets(ActiveSheet.Name).Cells(Rows.Count, "B").End(xlUp).Row
For X = 1 To lRow
If InStr(1, ThisWorkbook.Sheets(ActiveSheet.Name).Range("$B$" & X), "") > 0 Then
target_sheet.Range("$A$" & X) = ActiveSheet.Name
End If
Next
Try :
If InStr(1, ThisWorkbook.Sheets(ActiveSheet.Name).Range("$B$" & X), "") > 0 Then
Seems like, for some reason, you've lost 4 letters.
I found the answer to be:
Sub Export_PB_uge()
Dim pb_uge As Worksheet
Dim myPath As String
Dim MyFileName As String
Dim x As Long
Dim wsCSV As Worksheet
myPath = "C:mypath1"
MyFileName = Sheets("Front_Page").Range("g6").Value
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
If Not Right(myPath, 1) = "\" Then myPath = myPath & "\"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
With ThisWorkbook.Sheets("PB_uge")
If .FilterMode Then pb_uge.ShowAllData
.Visible = True
.Copy
End With
Set wsCSV = ActiveWorkbook.Sheets(1)
With wsCSV
.Range("A1").EntireRow.Delete
.Range("A1").EntireColumn.Insert
.Range("A1").Value = "Department"
lRow = .Cells(Rows.Count, "C").End(xlUp).Row
.Range("A2:A" & lRow) = ThisWorkbook.Sheets("Front_Page").Range("g6").Value
.Parent.SaveAs Filename:= _
myPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False, _
Local:=True
.Parent.Close False
End With
ThisWorkbook.Sheets("PB_uge").Visible = False
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "CSV saved at " & myPath & MyFileName, vbInformation
End Sub

Hyperlinking .mpg files to cells in excel

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