Paste same hyperlink to all sheets - excel

I have a hyperlink on cell B1 of Sheet1. I would like to copy this exact hyperlink to cell B1 of all sheets in my workbook.
I tried copying the link, selecting all sheets and pasting, but this is not working for some reason. I also have over 50 sheets.
Update: Here's what I tried. It pastes the 'hyperlink' on all sheets in the workbook, but the hyperlink does not work for some reason.
Sub ReturnToSheet1()
Dim ws As Worksheet
For Each ws In Worksheets
If ws.Name <> "Sheet1" Then
ws.Activate
Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("B1").Select
ActiveCell.FormulaR1C1 = "return to sheet1"
Rows("2:2").Select
Selection.RowHeight = 7.5
Range("B1").Select
ActiveCell.FormulaR1C1 = "return to sheet1"
Range("B1").Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _
"Sheet1!A1", TextToDisplay:="return to sheet1"
With Selection.Font
.Name = "Calibri"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleSingle
.ThemeColor = xlThemeColorHyperlink
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
Selection.Font.Size = 11
Range("A3").Select
End If
Next ws
End Sub
Thanks.

I think you are making this more complicated than it needs to be:
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If ws.Name <> "Sheet1" Then
ws.Hyperlinks.Add _
Anchor:=ws.Range("B1"), _
Address:="", _
SubAddress:="Sheet1!A1", _
TextToDisplay:="return to sheet1"
End If
Next ws
Should be enough to do the job

Related

Create dynamic pivot sheets with defined sheet name

**I m trying to create three different sheets with this Macro code. So when i run this code those the sheets are creating as it should, but i want to rename these sheets created with particular name and delete them or replace them when i run the code again.
So the below code is the modified in such a way that it creates 2 pivot sheet and one sheet with data that creates the count of range defined... with countifs
SO when i searched the internet for an alternative i tried the other code but the but the range(dynamic) is not getting selected while creating pivot table. it throws an error
SetwsPT=wb.Worksheets.Add
Please help.
Sub MacroPivotReceivedResolved()
Sheets.Add
pivotWS = ActiveSheet.Name
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"ReceivedMacro!R6C1:R20000C54", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:=pivotWS & "!R3C1", TableName:="PivotTable5" _
, DefaultVersion:=xlPivotTableVersion15
Sheets(pivotWS).Select
Cells(3, 3).Select
ActiveSheet.PivotTables("PivotTable5").RowAxisLayout xlTabularRow
With ActiveSheet.PivotTables("PivotTable5").PivotFields("Receipt Date")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable5").AddDataField ActiveSheet.PivotTables( _
"PivotTable5").PivotFields("Receipt Date"), "Count of Case Age", xlCount
Sheets("ResolvedMacro").Select
Range("A6").Select
Sheets.Add
pivotWS1 = ActiveSheet.Name
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"ResolvedMacro!R6C1:R20000C54", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:=pivotWS1 & "!R3C1", TableName:="PivotTable6" _
, DefaultVersion:=xlPivotTableVersion15
Sheets(pivotWS1).Select
Cells(3, 3).Select
With ActiveSheet.PivotTables("PivotTable6").PivotFields("Resolved Date")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable6").AddDataField ActiveSheet.PivotTables( _
"PivotTable6").PivotFields("Resolved Date"), "Count of Case Age", xlCount
Sheets("ReceivedMacroAge").Select
Range("A6").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets.Add After:=ActiveSheet
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
With Selection
.VerticalAlignment = xlTop
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlLTR
.MergeCells = False
End With
Columns("A:A").ColumnWidth = 16.29
Cells.Select
Selection.ColumnWidth = 17.57
Columns("J:J").Select
Selection.Insert Shift:=xlToRight
Range("J2").Select
ActiveCell.FormulaR1C1 = "=COUNT"
Columns("J:J").Select
Selection.Delete Shift:=xlToLeft
Rows("1:1").Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Range("H1").Select
ActiveCell.FormulaR1C1 = "Total Outstanding"
Range("I1").Select
ActiveCell.FormulaR1C1 = "=SUM(R[1]C:R[5]C)"
Range("H2").Select
ActiveCell.FormulaR1C1 = "Over 8 Weeks (Over 56 Days)"
Range("I2").Select
ActiveCell.FormulaR1C1 = "=COUNTIFS(R[9]C:R[1000]C, "">=57"")"
Range("H3").Select
ActiveCell.FormulaR1C1 = "6-8 Weeks (42-56 days)"
Range("I3").Select
ActiveCell.FormulaR1C1 = _
"=SUMPRODUCT(INT(R[9]C:R[1000]C>=42), INT(R[9]C:R[1000]C<57))"
Range("H4").Select
ActiveCell.FormulaR1C1 = "4-6 weeks (28 - 41)"
Range("I4").Select
ActiveCell.FormulaR1C1 = _
"=SUMPRODUCT(INT(R[9]C:R[1000]C>=28), INT(R[9]C:R[1000]C<42))"
Range("H5").Select
ActiveCell.FormulaR1C1 = "2-4 Weeks (14 - 27)"
Range("I5").Select
ActiveCell.FormulaR1C1 = _
"=SUMPRODUCT(INT(R[9]C:R[1000]C>=14), INT(R[9]C:R[1000]C<28))"
Range("H6").Select
ActiveCell.FormulaR1C1 = "0-2 Weeks (0-13)"
Range("I6").Select
ActiveCell.FormulaR1C1 = _
"=SUMPRODUCT(INT(R[9]C:R[1000]C>=1), INT(R[9]C:R[1000]C<14))"
Range("H7").Select
ActiveCell.FormulaR1C1 = "Cases to breach next day ( Day 56)"
Range("I7").Select
ActiveCell.FormulaR1C1 = "=COUNTIFS(R[9]C:R[1000]C, ""=56"")"
Range("H8").Select
End Sub
Here's a basic example of how to remove and replace a worksheet:
Sub MacroPivotReceivedResolved()
Const PIVOTA_NAME As String = "Pivot A"
Dim wsPivot As Worksheet, wb As Workbook, pc As PivotCache, pt As PivotTable
Set wb = ThisWorkbook 'for example
DeleteSheet wb, PIVOTA_NAME 'delete the sheet if it exists
Set wsPivot = wb.Sheets.Add 'add new sheet for pivot table
wsPivot.Name = PIVOTA_NAME
'create the pivot cache
Set pc = wb.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:="ReceivedMacro!R6C1:R20000C54", _
Version:=xlPivotTableVersion15)
'create the pivot table
Set pt = pc.CreatePivotTable(TableDestination:=pivotWS.Range("A3"), _
TableName:="PivotTable5", _
DefaultVersion:=xlPivotTableVersion15)
'now you can use `pt` instead of `ActiveSheet.PivotTables("PivotTable5")`
pt.RowAxisLayout xlTabularRow
With pt.PivotFields("Receipt Date")
.Orientation = xlRowField
.Position = 1
End With
pt.AddDataField pt.PivotFields("Receipt Date"), "Count of Case Age", xlCount
End Sub
'Remove any worksheet named `wsName` from workbook `wb`,
' ignoring any error if no sheet with that name is found
Sub DeleteSheet(wb As Workbook, wsName As String)
Dim ws As Worksheet, da As Boolean
On Error Resume Next 'ignore error if sheet doesn't exist
Set ws = wb.Worksheets(wsName)
On Error GoTo 0 'stop ignoring errors
If Not ws Is Nothing Then
da = Application.DisplayAlerts 'get current setting
Application.DisplayAlerts = False 'turn off alerts
wb.Worksheets(wsName).Delete
Application.DisplayAlerts = da 'restore previous setting
End If
End Sub

Excel VBA sheet name list with maxing colors

I am trying to write a VBA function where I produce a new sheet, give a lists of all the sheet names in the workbook and match the cell color of the sheet name, with the tab color of the sheet name. The pseudocode will look something like this:
Create a new sheet
Loop through all sheets in the workbook
Write down the sheet name in the created sheet
Retrieve the sheet ThemeColor (e.g. xlThemeColorLight2)
Retrieve the sheet TintAndShade (e.g. 0.799981688894314
Set the cell in which the name of the sheet is to the correct ThemeColor and TintAndShade
End
Is there a way in which this is possible?
Sub SheetList()
Dim ws As Worksheet
Dim x As Integer
x = 1
Sheets.Add
sheet_name = InputBox("Please enter a sheet name")
ActiveSheet.Name = sheet_name # Create a new sheet name
For Each ws In Worksheets
Sheets(sheet_name).Cells(x, 1) = ws.Name # Set cell value to sheet name
Dim theme_color As String
Dim tint_and_shade As Single
theme_color = ... # Attain sheet ThemeColor of current ws here
tint_and_shade = ... # Attain sheet TintAndShade of current ws here
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = theme_color # Set current cell to theme_color
.TintAndShade = tint_and_shade # Set current cell to tint_and_shade
.PatternTintAndShade = 0
End With
x = x + 1
Next ws
You can use ws.Tab.ThemeColor and ws.Tab.TintAndShade to retrieve those values.
I updated your code so that you can use the wsNewvariable to refer to the new worksheet.
Furthermore I am checking that only color codes of the other worksheets are checked.
Sub SheetList()
Dim wsNew As Worksheet
With ThisWorkbook.Worksheets
Set wsNew = .Add(.Item(1))
End With
Dim sheet_name
sheet_name = InputBox("Please enter a sheet name")
wsNew.Name = sheet_name ' Create a new sheet name
Dim ws As Worksheet, c As Range, x As Long
For Each ws In Worksheets
If Not ws Is wsNew Then
x = x + 1
Set c = wsNew.Cells(x, 1)
c.Value = ws.Name ' Set cell value to sheet name
Dim theme_color As Single
Dim tint_and_shade As Single
theme_color = ws.Tab.ThemeColor ' Attain sheet ThemeColor of current ws here
tint_and_shade = ws.Tab.TintAndShade ' Attain sheet TintAndShade of current ws here
With c.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
If theme_color > 0 Then
.ThemeColor = theme_color ' Set current cell to theme_color
End If
.TintAndShade = tint_and_shade ' Set current cell to tint_and_shade
.PatternTintAndShade = 0
End With
End If
Next ws
End Sub
Thanks for your help Ike. I made a full piece of code to get a sheet overview page. It is not the most elegant piece of code, but here it is:
Sub SheetOverview()
'
' SheetOverview
'
Dim ws As Worksheet
Dim x As Integer
Dim c As Range
x = 1
' Add new sheet, ask user for sheet name
Sheets.Add
ActiveWindow.DisplayGridlines = False
sheet_name = InputBox("Please enter a sheet name")
ActiveSheet.Name = sheet_name
' Loop to obtain all sheet names
For Each ws In Worksheets
Set c = Sheets(sheet_name).Cells(x, 1)
c.Value = ws.Name
Dim theme_color As Single
Dim tint_and_shade As Single
theme_color = ws.Tab.ThemeColor ' Attain sheet ThemeColor of current ws here
tint_and_shade = ws.Tab.TintAndShade ' Attain sheet TintAndShade of current ws here
With c.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
If theme_color > 0 Then
.ThemeColor = theme_color ' Set current cell to theme_color
End If
.TintAndShade = tint_and_shade ' Set current cell to tint_and_shade
.PatternTintAndShade = 0
End With
x = x + 1
Next ws
' Cut selection
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Cut
Range("A6").Select
ActiveSheet.Paste
' Enter Sheets and Description and format
Range("A5").Select
ActiveCell.FormulaR1C1 = "Sheets"
Range("B5").Select
ActiveCell.FormulaR1C1 = "Description"
Range("A5:B5").Select
Selection.Font.Bold = True
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
Selection.Borders(xlEdgeRight).LineStyle = xlNone
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
' Format title
Range("A4").Select
Selection.End(xlUp).Select
Selection.Font.Bold = True
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.149998474074526
.PatternTintAndShade = 0
End With
Selection.Font.Size = 14
Range("A2").Select
ActiveCell.FormulaR1C1 = "Author:"
Range("B2").Select
ActiveCell.FormulaR1C1 = "[Enter author here]"
Selection.Font.Italic = True
Range("A3").Select
ActiveCell.FormulaR1C1 = "Date:"
Range("B3").Select
ActiveCell.FormulaR1C1 = "=TODAY()"
Selection.Copy
Range("B3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Rows("4:4").Select
Selection.Insert Shift:=xlDown
Selection.Borders(xlLeft).LineStyle = xlNone
Selection.Borders(xlRight).LineStyle = xlNone
Selection.Borders(xlTop).LineStyle = xlNone
Selection.Borders(xlBottom).LineStyle = xlNone
Range("A4").Select
ActiveCell.FormulaR1C1 = "Time:"
Range("B4").Select
ActiveCell.FormulaR1C1 = "=NOW()-TODAY()"
Range("B4").Select
Selection.Copy
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.NumberFormat = "[$-x-systime]h:mm:ss AM/PM"
Columns("A:B").Select
Range("A5").Activate
Selection.Columns.AutoFit
Range("B1").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.149998474074526
.PatternTintAndShade = 0
End With
Columns("B:B").ColumnWidth = 52.11
Range("B3:B4").Select
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("A1").Select
End Sub
Insert Sheet List
Sub InsertSheetList()
' Define constants.
Const Title As String = "Insert Sheet List"
Const FIRST_CELL As String = "A1"
Dim Headers() As Variant
Headers = VBA.Array("Index", "Color", "Name", "Type")
' Attempt to reference the workbook.
Dim wb As Workbook: Set wb = ActiveWorkbook
If wb Is Nothing Then
MsgBox "No visible workbooks open.", vbExclamation, Title
Exit Sub
End If
' Input sheet name.
Dim SheetName As String
SheetName = InputBox("Please enter a sheet name", Title)
If Len(SheetName) = 0 Then
MsgBox "Dialog canceled.", vbExclamation
Exit Sub
End If
' Add a worksheet to be the first and reference it.
wb.Sheets.Add Before:=wb.Sheets(1)
Dim dws As Worksheet: Set dws = wb.Sheets(1)
' Attempt to rename the worksheet.
Dim ErrNum As Long
On Error Resume Next
dws.Name = SheetName
ErrNum = Err.Number
On Error GoTo 0
If ErrNum <> 0 Then
Application.DisplayAlerts = False
dws.Delete
Application.DisplayAlerts = True
MsgBox "Couldn't use '" & SheetName & "' for a sheet name.", _
vbExclamation, Title
Exit Sub
End If
' Calcuate the number of columns (headers).
Dim ColumnsCount As Long: ColumnsCount = UBound(Headers) + 1
' Write the headers.
Dim drg As Range
Set drg = dws.Range(FIRST_CELL).Resize(, ColumnsCount)
drg.Value = Headers
' Write the list.
Dim sh As Object
Dim r As Long
For Each sh In wb.Sheets
r = r + 1
If r > 1 Then
Set drg = drg.Offset(1)
drg.Cells(1).Value = sh.Index
drg.Cells(2).Interior.Color = sh.Tab.Color
drg.Cells(3).Value = sh.Name
drg.Cells(4).Value = TypeName(sh)
End If
Next sh
' Autofit.
dws.Columns(1).Resize(, ColumnsCount).AutoFit
' Inform.
MsgBox "Sheet list created.", vbInformation, Title
End Sub

my code is long and would like to know if it can be done better

I've written the following code and would ask you experts if there is an way to write it better.
in a nutshell it clears the datatable and keep the formulas,
then it imports data from another sheet and saves it asa new file. then changes columns to value and dates.
after that it copies an column to the last column and separates it and shows online the first few characters.
at last I make a new sheet within were some filtering is done.
in short the code is working but I believe it can be done better and quicker.
Sub Openstaande_inslagen()
Application.ScreenUpdating = False
Call deletekeepformulas
Call COMMISSIE_EXTRAHEREN
Call PivotC
ActiveWorkbook.RefreshAll
End Sub
' ----------------------------------------------------------------
' Purpose: Delete table data and keep table formulas
' ----------------------------------------------------------------
Sub deletekeepformulas()
Dim tbl As ListObject
'Assign table to a variable
Set tbl = ThisWorkbook.Sheets("Inslagen").ListObjects("Tabel1")
'Delete table data and keep formulas
If Not tbl.DataBodyRange Is Nothing Then
tbl.DataBodyRange.Delete
End If
Call wb
Call AllWorksheetPivots
Call Save_Workbook_NewName
Call Convert_getal
Call Convert_getal2
End Sub
Sub wb()
Code:
Dim WB1 As Workbook
Dim WB2 As Workbook
' Capture current workbook
Set WB1 = ActiveWorkbook
' Open new workbook
Call OpenNewBox
' Capture new workbook
Set WB2 = ActiveWorkbook
ActiveSheet.UsedRange.Copy
' Go back to original workbook
WB1.Activate
Sheets("Inslagen").Cells(1, 1).PasteSpecial Paste:=xlPasteValues
End Sub
Sub OpenNewBox()
Dim xFilePath As String
Dim xObjFD As FileDialog
Set xObjFD = Application.FileDialog(msoFileDialogFilePicker)
With xObjFD
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xls; *.xlsx; *.xlsm; *.xlsb", 1
.Show
If .SelectedItems.Count > 0 Then
xFilePath = .SelectedItems.Item(1)
Else
Exit Sub
End If
End With
Workbooks.Open xFilePath
End Sub
Sub AllWorksheetPivots()
'Updateby20140724
Dim xTable As PivotTable
For Each xTable In Application.ActiveSheet.PivotTables
xTable.RefreshTable
Next
End Sub
Sub Save_Workbook_NewName()
Dim workbook_Name As Variant
workbook_Name = Application.GetSaveAsFilename(FileFilter:="Excel Macro-Enabled Workbook (*.xlsm),*.xlsm")
If workbook_Name <> False Then
ActiveWorkbook.SaveAs Filename:=workbook_Name
End If
End Sub
Sub COMMISSIE_EXTRAHEREN()
'
' COMMISSIE_EXTRAHEREN Macro
' artikelnummer laten splitsen om zo alleen het commissienummer over te houden
'
'
Sheets("inslagen").Activate
ActiveSheet.ListObjects("Tabel1").ListColumns(15).DataBodyRange.Select
Selection.Copy
ActiveSheet.ListObjects("Tabel1").ListColumns(19).DataBodyRange.Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("S1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "Commissie"
Range("S2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.TextToColumns Destination:=Range("S2"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:=":", FieldInfo:=Array(Array(1, 1), Array(2, 9)), TrailingMinusNumbers:=True
Call MultipleRange_DATE
Call MultipleRange_NUMBER
End Sub
Sub Convert_getal()
Columns("A:A").Select
With Selection
.NumberFormat = "dd-mm-yyyy"
.Value = .Value
End With
End Sub
Sub Convert_getal2()
Columns("E:F").Select
With Selection
.NumberFormat = "General"
.Value = .Value
End With
End Sub
Sub MultipleRange_DATE()
Dim r1 As Range, r2 As Range, r3 As Range, r4 As Range, r5 As Range, myMultipleRange As Range
Set r1 = Sheets("Inslagen").Range("G:G")
Set r2 = Sheets("Inslagen").Range("H:H")
Set r3 = Sheets("Inslagen").Range("K:K")
Set r4 = Sheets("Inslagen").Range("L:L")
Set r5 = Sheets("Inslagen").Range("T:T")
Set myMultipleRange = Union(r1, r2, r3, r4, r5)
myMultipleRange.NumberFormat = "dd-mm-yyyy"
End Sub
Sub MultipleRange_NUMBER()
Dim r1 As Range, r2 As Range, myMultipleRange As Range
Set r1 = Sheets("Inslagen").Range("A:A")
Set r2 = Sheets("Inslagen").Range("E:F")
Set myMultipleRange = Union(r1, r2)
myMultipleRange.NumberFormat = "General"
End Sub
Sub PivotC()
Sheets("nog afronden").Select
Columns("A:A").Select
With Selection
.NumberFormat = "dd-mm-yyyy"
.Value = .Value
Sheets.Add After:=ActiveSheet
ActiveSheet.Select
ActiveSheet.Name = "Bijna_afgerond"
Sheets("nog afronden").PivotTables("Draaitabel2").TableRange1.Copy Destination:=Worksheets("Bijna_afgerond").Range("A1")
Call DeleteEntireRows
Sheets("Bijna_afgerond").Activate
' SPATIES Macro
Rows("1:1").Select
Selection.Replace What:=" ", Replacement:="_", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
End With
Call DelLR2
Call ADD_COLUMN_TO_TABLE
Call Convert_getal3
Call DetermineActiveTable
Call Calculate_AF
End Sub
Sub DeleteEntireRows()
Sheets("Bijna_afgerond").Activate
Rows("1:2").EntireRow.Delete
Call Generate_Table
End Sub
Sub Generate_Table()
Dim tb2 As Range
Dim wsht As Worksheet
Set tb2 = Range("A1").CurrentRegion
Set wsht = ActiveSheet
wsht.ListObjects.Add(SourceType:=xlSrcRange, Source:=tb2).Name = "TEST_RANGE"
End Sub
Sub DelLR2()
Dim x As Long
With Sheets("Bijna_afgerond")
'Assumes last row of data found in column A (1)
x = .Cells(.Rows.Count, 1).End(xlUp).Row
.Cells(x, 2).EntireRow.Delete
End With
Worksheets("Bijna_afgerond").Cells.EntireColumn.AutoFit
End Sub
Sub DetermineActiveTable()
Dim SelectedCell As Range
Dim TableName As String
Dim ActiveTable As ListObject
Set SelectedCell = ActiveCell
'Determine if ActiveCell is inside a Table
On Error GoTo NoTableSelected
TableName = SelectedCell.ListObject.Name
Set ActiveTable = ActiveSheet.ListObjects(TableName)
On Error GoTo 0
'Do something with your table variable (ie Add a row to the bottom of the ActiveTable)
ActiveTable.Range.AutoFilter field:=6, Criteria1:="<>"
Exit Sub
'Error Handling
NoTableSelected:
MsgBox "There is no Table currently selected!", vbCritical
End Sub
Sub Convert_getal3()
Dim myRange As Range
Set myRange = Selection
ActiveSheet.ListObjects("TEST_RANGE").ListColumns("Referentie").Range.Select
With Selection
.NumberFormat = "general"
.Value = .Value
End With
End Sub
Sub Bijna_afgerond()
'
' BIJNA_AFGEROND Macro
' kijken naar een lijst met Bijna_afgeronde inslagen
'
'
Sheets("nog afronden").Select
ActiveSheet.PivotTables("Draaitabel2").RepeatAllLabels xlRepeatLabels
Range("A7").Select
Range("A7:F94").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("nog afronden").Select
Sheets.Add After:=ActiveSheet
Sheets("Blad2").Select
Sheets("Blad2").Name = "Bijna_afgerond"
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.AutoFilter
Cells.Select
Cells.EntireColumn.AutoFit
ActiveSheet.Range("$A$2:$F$89").AutoFilter field:=6, Criteria1:="<>"
Range("G3").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=RC[-2]-RC[-1]"
Range("G3").Select
Selection.FillDown
Selection.FormatConditions.AddColorScale ColorScaleType:=3
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
xlConditionValueLowestValue
With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
.Color = 8109667
.TintAndShade = 0
End With
Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
xlConditionValuePercentile
Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
.Color = 8711167
.TintAndShade = 0
End With
Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
xlConditionValueHighestValue
With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
.Color = 7039480
.TintAndShade = 0
End With
Sheets("nog afronden").Select
ActiveSheet.PivotTables("Draaitabel2").RepeatAllLabels xlRepeatLabels
End Sub
Sub ADD_COLUMN_TO_TABLE()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim tbl As ListObject
Set tbl = ws.ListObjects("TEST_RANGE")
'add a new column at the end of the table
tbl.ListColumns.Add.Name = "Percentage_voltooid"
ActiveSheet.Columns("A:G").AutoFit
End Sub
Sub Calculate_AF()
Dim tbl As ListObject
Dim sFormula As String
Set tbl = Sheets("Bijna_afgerond").ListObjects("TEST_RANGE")
sFormula = "=[#[Som_van_Aantal_verwacht]]-[#[Som_van_Aantal_ontvangen2]]"
tbl.ListColumns("Percentage_voltooid").DataBodyRange.Cells(1).Formula = sFormula
tbl.ListColumns("Percentage_voltooid").DataBodyRange.Cells().Select
Selection.FormatConditions.AddColorScale ColorScaleType:=3
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
xlConditionValueLowestValue
With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
.Color = 8109667
.TintAndShade = 0
End With
Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
xlConditionValuePercentile
Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
.Color = 8711167
.TintAndShade = 0
End With
Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
xlConditionValueHighestValue
With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
.Color = 7039480
.TintAndShade = 0
End With
End Sub
Sub VOORWAARDELIJKE_OPMAAK()
'
' VOORWAARDELIJKE_OPMAAK Macro
'
'
Range("G45").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.FormatConditions.AddColorScale ColorScaleType:=3
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
xlConditionValueLowestValue
With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
.Color = 8109667
.TintAndShade = 0
End With
Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
xlConditionValuePercentile
Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
.Color = 8711167
.TintAndShade = 0
End With
Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
xlConditionValueHighestValue
With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
.Color = 7039480
.TintAndShade = 0
End With
End Sub

Pasting as link errors out

I wrote a code with a loop that copies a special cell in a source workbook and then opens another workbook and pastes a copied number to a special cell, and after seven times I get this error:
this is my code:
ActiveSheet.Paste Link:=True
I don't understand why it happens.
Sub Shadow()
ActiveSheet.Range("$A$1:$I$9627").AutoFilter Field:=4, Criteria1:="basic"
' Copy filtered worksheet
Number = Application.WorksheetFunction.Subtotal(3, Range("A1:A500000"))
ActiveSheet.Range("$A$1:$I$9627").SpecialCells(xlCellTypeVisible).Copy
' Addition of new sheet
Sheets.Add
ActiveSheet.Paste
' Calculating number of rows
finalrow = Cells(Rows.Count, 1).End(xlUp).Row
' A loop for copying row by row number and date then opening shadowgraph for pasting copied data
Dim i1 As Integer
For i1 = 2 To finalrow
ActiveSheet.Cells(i1, 1).Copy
Workbooks.Open Filename:="E:\Attachment\PCI\Clutch disc\FLEXIBALE (RO)\Shadowgraph.xlsm"
Windows("Shadowgraph.xlsm").Activate
Range("AW5").Select
ActiveSheet.Paste Link:=True
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Windows("ball99.xlsm").Activate
' Representing relative name for saving documents
Dim Name1 As String
Name1 = ActiveSheet.Cells(i1, 2) & "Shadowgraph"
ActiveSheet.Cells(i1, 2).Copy
Windows("Shadowgraph.xlsm").Activate
Range("E32").Select
ActiveSheet.Paste Link:=True
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
' Set work directory
ChDir "E:\Attachment\PCI\Clutch disc\FLEXIBALE (RO)"
' Set saving address
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"E:\Attachment\PCI\Clutch disc\FLEXIBALE (RO)\" & _
Name1, Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Windows("Shadowgraph.xlsm").Activate
' Closing opened datasheets
Windows("Shadowgraph.xlsm").Close (False)
Next i1
Windows("ball99.xlsm").Activate
' Closing every sheets except main workbook 01
Dim ws1 As Worksheet
For Each ws1 In ActiveWorkbook.Worksheets
If ws1.Name <> "01" Then ws1.Visible = xlSheetHidden
Next ws1
' Clearing all fiters
ActiveSheet.ShowAllData
End Sub

Copy data from multiple sheets into multiple sheets in new workbook

I know variations of this question have been asked but I can't seem to find the right code to accomplish this task. I have 2 tabs, Master Summary and Master Detail, from which I would like to copy data based on cell values in columns K and G respectively. I would like to copy data from both tabs into a new workbook if the values where these columns match. Each value needs its own workbook to be saved as the name in the cell.
Thanks
Here is what I came up with:
Sub CopyCMOsToOwnWorkbooks()
Application.EnableCancelKey = xlDisabled
Application.ScreenUpdating = False
Dim CMO As Variant
Dim CMOS As Variant
Dim wbDest As Workbook
Dim RAF As Workbook
Set RAF = ThisWorkbook
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
CMOS = Array("Element Care", "CCACG EAST", "SCMO", "CCACG WEST", "Uphams Corner Hlth Cent", "CCC-Boston", "Vinfen", "Behavioral Hlth Ntwrk", _
"CommH Link Worc", "Long Term Care CMO", "Advocates, Inc", "CCC-Springfield", "BU Geriatric Service", "Lynn Comm HC", "CCA-BHI", "BIDJP Subacute", _
"CCC-Lawrence", "CCC-Framingham", "East Boston Neighborhoo", "BosHC 4 Homeless", "Bay Cove Hmn Srvces", "Mailhoit, Carrie", "Brightwood Hlth Ctr-Bay", _
"Romero, Michele", "Isaacs, Cindy", "McCoy, Viola", "ADRC of Greater North Shore", "Geller, Marian")
For Each CMO In CMOS
On Error Resume Next
RAF.Activate
Application.CutCopyMode = False
Sheets("MASTER Summary").Select
Range("F12").Select
Selection.AutoFilter
ActiveSheet.ListObjects("Table_Query_from_ProdServerP052").Range.AutoFilter _
Field:=11, Criteria1:=CMO
Cells.Select
Selection.Copy
Set wbDest = Workbooks.Add(xlWBATWorksheet)
ActiveSheet.Paste
ActiveSheet.Cells.Select
Selection.ColumnWidth = 8.29
Cells.EntireColumn.AutoFit
Selection.ColumnWidth = 78.71
Cells.EntireRow.AutoFit
Cells.EntireColumn.AutoFit
Sheets("Sheet1").Select
Sheets("Sheet1").Name = "Summary"
Range("C24").Select
ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes).Name = _
"Table1"
Range("Table1[#All]").Select
ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight13"
RAF.Activate
Application.CutCopyMode = False
Sheets("MASTER Detail").Select
Range("A2").Select
Selection.AutoFilter
ActiveSheet.ListObjects("Table_Query_from_ProdServerP054").Range.AutoFilter _
Field:=7, Criteria1:=CMO
Cells.Select
Selection.Copy
wbDest.Activate
Sheets.Add After:=ActiveSheet
Range("A1").Select
ActiveSheet.Paste
Cells.Select
Selection.ColumnWidth = 34.29
Selection.ColumnWidth = 50.71
Cells.EntireRow.AutoFit
Cells.EntireColumn.AutoFit
wbDest.Sheets("Sheet2").Select
wbDest.Sheets("Sheet2").Name = "Detail"
ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes).Name = _
"Table2"
Range("Table2[#All]").Select
ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight13"
Range("A13").Select
wbDest.Sheets("Summary").Select
Application.DisplayAlerts = False
wbDest.SaveAs ThisWorkbook.Path & Application.PathSeparator & _
CMO & " " & Format(Date, "mmm_dd_yyyy")
Application.DisplayAlerts = True
wbDest.Close
Next CMO
End Sub

Resources