VBA copy a range based on values from 2 separate sheets - excel

I do not know what I am doing wrong. The code will run but it does not copy the data as expected, all the values seem to be overwriting to row 1 on the target sheet (tsht) instead of copying data down the target sheet. The goal here is to take data and iterate it for every county listed on the group ID tab (captured by SubCell.Value). Where plan codes and term dates match, the macro should copy each matching row from dsht for the indicated number of counties on gsht to the tsht. Can anyone see my error or why this code is keeping data all in the top row of the tsht?
Sub GroupID_Breakout()
Dim dsht As Worksheet 'data sheet target
Dim gsht As Worksheet
Dim tsht As Worksheet
Dim dlrow As Long
Dim glrow As Long
Dim tlrow As Long
Dim SubCell As Range
Dim rngCell As Range
Dim Result() As String
Dim countycount As Long
Set dsht = ThisWorkbook.Worksheets("Data_No Formulas")
Set gsht = ThisWorkbook.Worksheets("GroupID")
'kill clunky processes
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
'delete compare tab if it exists
Application.DisplayAlerts = False
On Error Resume Next
ThisWorkbook.Sheets("Data_Final").Delete
On Error GoTo 0
Application.DisplayAlerts = True
'On Error GoTo Errhandler
Sheets.Add(After:=Sheets("Data_No Formulas")).Name = "Data_Final" 'create new tab
Set tsht = ThisWorkbook.Worksheets("Data_Final")
With dsht.Range("A2:CN2")
tsht.Range("A1").Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
glrow = gsht.Cells(Rows.Count, 1).End(xlUp).Row
dlrow = dsht.Cells(Rows.Count, 1).End(xlUp).Row
For Each SubCell In gsht.Range("I2:I" & glrow)
countycount = SubCell.Value
Result() = Split(SubCell.Offset(0, -2).Value, ",")
For Each rngCell In dsht.Range("A3:A" & dlrow)
a = 0
If SubCell.Offset(0, -4).Value = rngCell.Value And SubCell.Offset(0, -8).Value = rngCell.Offset(0, 5).Value Then
For i = 1 To countycount
tlrow = tsht.Cells(Rows.Count, 1).End(xlUp).Row
With dsht.Range(rngCell, rngCell.Offset(0, 91))
tsht.Range("A" & tlrow).Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
tsht.Range("L" & tlrow).Value = Result(a)
i = i + 1
Next
a = a + 1
End If
Next rngCell
Next SubCell
'bring back clunky processes
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.Calculation = xlCalculationAutomatic
MsgBox ("Macro Complete!")
Exit Sub
Errhandler:
'bring back clunky processes
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.Calculation = xlCalculationAutomatic
Select Case Err.Number
'different error handling here
Case Else
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Summary"
End Select
End Sub
This has been resolved with the below code, I wanted to post the resolution in case anyone finds a way to make this code work for them. Sorry I couldn't get this to copy over as clean as my 1st block.
Solution:
Sub GroupID_Breakout()
Dim dsht As Worksheet 'data sheet target
Dim gsht As Worksheet
Dim tsht As Worksheet
Dim dlrow As Long
Dim glrow As Long
Dim tlrow As Long
Dim SubCell As Range
Dim rngCell As Range
Dim Result() As String
Dim countycount As Long
Set dsht = ThisWorkbook.Worksheets("Data_No Formulas")
Set gsht = ThisWorkbook.Worksheets("GroupID")
'kill clunky processes
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
'delete compare tab if it exists
Application.DisplayAlerts = False
On Error Resume Next
ThisWorkbook.Sheets("Data_Final").Delete
On Error GoTo 0
Application.DisplayAlerts = True
'On Error GoTo Errhandler
Sheets.Add(After:=Sheets("Data_No Formulas")).Name = "Data_Final" 'create new tab
Set tsht = ThisWorkbook.Worksheets("Data_Final")
'pull header from dsht to tsht
With dsht.Range("A2:CN2")
tsht.Range("A1").Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
glrow = gsht.Cells(Rows.Count, 1).End(xlUp).Row
dlrow = dsht.Cells(Rows.Count, 1).End(xlUp).Row
For Each SubCell In gsht.Range("I2:I" & glrow)
countycount = SubCell.Value
Result() = Split(SubCell.Offset(0, -2).Value, ",") 'separates a list of counties by comma to reference as "Result(0)"
For Each rngCell In dsht.Range("A3:A" & dlrow)
a = 0
i = 1
For i = 1 To countycount
If SubCell.Offset(0, -4).Value = rngCell.Value And SubCell.Offset(0, -8).Value = rngCell.Offset(0, 5).Value Then 'match dates and plan codes
'move row where match is found between dsht and gsht variables
With dsht.Range(rngCell, rngCell.Offset(0, 91))
tlrow = tsht.Cells(Rows.Count, 1).End(xlUp).Row
tsht.Range("A" & (tlrow + 1)).Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
'place county names captured by split above with each iteration
tsht.Range("L" & (tlrow + 1)).Value = Result(a)
End If
a = a + 1
Next i
Next rngCell
Next SubCell
'bring back clunky processes
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.Calculation = xlCalculationAutomatic
MsgBox ("Macro Complete!")
Exit Sub
Errhandler:
'bring back clunky processes
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.Calculation = xlCalculationAutomatic
Select Case Err.Number
'different error handling here
Case Else
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Summary"
End Select
End Sub

tsht.Range("A" & tlrow).Resize(.Rows.Count, .Columns.Count).Value =
should be
tsht.Range("A" & (tlrow+1)).Resize(.Rows.Count, .Columns.Count).Value =

Related

Freeze on specific sheet during macro execution and loop through each sheet containing a specific name

The parts not working are especially loop parts (marked as --- not working ---). Do I have to “activate” them first somehow?
The part which displays sheet “X” and freezing the screen isn't working too.
I want to display a picture on sheet “X” with a coffee image and the message: “please wait” until the macro is finished.
I tried to avoid the “Select” and “Activate” commands.
'Variables
Dim Destbook As Workbook
Dim Sourcebook As Workbook
Dim DestCell As Range
Dim xFile As String
Dim xFolder As String
Dim xFiles As New Collection
Dim xSheets As Worksheet
Dim xCount As Long
Dim xSheetCount As Long
Dim xRow As Long
Dim A As Integer
Dim I As Integer
Dim Z As Integer
Dim xMax As Double
'On a System Error go to "Troubleshooting" and display the ocurred fault code
On Error GoTo Troubleshooting
'Deactivate Alerts
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.UseSystemSeparators = False
'Display hidden Sheet "X", select cell "A1" and freeze screen
' ------------------------- NOT WORKING ---------------------
ActiveWorkbook.Sheets("X").Visible = xlSheetVisible
With ActiveWorkbook.Sheets("X")
Application.Goto .Range("A1")
ActiveWindow.FreezePanes = True
End With
'Deactivate Alerts
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.UseSystemSeparators = False
'Delete contents for each Sheet containing the name "Data" for the selected range
' ------------------------- NOT WORKING ---------------------
xSheetCount = ActiveWorkbook.Worksheets.Count
For Z = 1 To xSheetCount '
If Left(xSheets.Name, 4) = "Data" Then
With ActiveSheet
.Range("B5:K90000").ClearContents
End With
End If
Next Z
'Select the folder with the desired data to import
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Folder"
.ButtonName = "Import Data"
.InitialView = msoFileDialogViewList
If .Show = -1 Then xFolder = .SelectedItems(1)
If Right(xFolder, 1) <> "\" Then xFolder = xFolder & "\"
End With
'On error or no files found display the following
If xFolder = "" Then
MsgBox ("No files found or selected!")
Exit Sub
End If
'Get the desired Textfiles in the selected Folder
Set FS = CreateObject("Scripting.FileSystemObject")
Set Folder = FS.Getfolder(xFolder)
For Each File In Folder.Files
If File.Name Like "*####-##-##*" Then
xFile = File.Name
If xFile <> "" Then
xCount = xCount + 1
xFiles.Add xFile, xFile
If xFile = "" Then Resume Next
End If
End If
Next
'File processing
I = 1
Set Destbook = ThisWorkbook
If xFiles.Count > 0 Then
For A = 1 To xFiles.Count
Set Sourcebook = Workbooks.Open(xFolder & xFiles.Item(A), local:=True)
'Skip files with no current values greater than 2 A
xMax = Application.WorksheetFunction.Max(Range("C2:C90000"))
If xMax < 2 Then
GoTo ContinueLoop
End If
If InStr(1, ActiveSheet.Name, "Stufe", vbTextCompare) <> 0 Then
Columns("I:Y").Delete
Rows(1).Insert
Range("D1").Value = ActiveSheet.Name
xRow = Cells(Rows.Count, 1).End(xlUp).Row
ActiveSheet.Range("A1:J" & xRow).Copy
End If
ThisWorkbook.Sheets("Data (" + CStr(I) + ")").Range("B3").PasteSpecial Paste:=xlPasteAll
Application.CutCopyMode = False
On Error Resume Next
On Error GoTo 0
I = I + 1
ContinueLoop: Sourcebook.Close False
Next
End If
'Just some formatting things...
' ------------------------- NOT WORKING ---------------------
xSheetCount = ActiveWorkbook.Worksheets.Count
For I = 1 To xSheetCount
If Left(Worksheet.Name, 4) = "Data" Then
With ActiveSheet.Range("A1:J" & xRow)
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
Range("B3:C3").Merge
Range("B3").Value = "Filename:"
Range("B3:K4").Font.Bold = True
Range("B4:K4").Borders.LineStyle = xlContinuous
End With
End If
Next I
'Delete sheet "Import data", hide sheet "X" and save file
'Sheets("Import data").Delete
ActiveWorkbook.Sheets("X").Visible = xlSheetVeryHidden
Application.DisplayAlerts = True
Application.ScreenUpdating = False
Application.UseSystemSeparators = True
'DestBook.SaveAs Filename:=CStr(Date) + "Analysis", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
'Display the occured error message and exit program
Troubleshooting: Application.DisplayAlerts = True
Application.ScreenUpdating = True
If Err.Number <> 0 Then MsgBox "Troubleshooting: " & _
Err.Number & vbLf & Err.Description: Err.Clear
Exit Sub
You should add some details about your data and/or your intention.
Using subprocedures could simplify your debugging task.
Avoid "On Error Goto xxx" during development as you need the error details while debugging.
Using "Option Explicit" as a first line simplifies your debugging.
I hope this helps a little! ;-)
Option Explicit
Sub ActivateAlerts_ShowSheetX()
'Activate Alerts
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.UseSystemSeparators = True
ActiveWorkbook.Sheets("X").Visible = xlSheetVisible
End Sub
Sub main()
'Variables
Dim Destbook As Workbook
Dim Sourcebook As Workbook
Dim DestCell As Range
Dim xFile As String
Dim xFolder As String
Dim xFiles As New Collection
Dim xSheets As Worksheet
Dim xCount As Long
Dim xSheetCount As Long
Dim xRow As Long
Dim aCt As Integer
Dim iCt As Integer
Dim zCt As Integer
Dim xMax As Double
'On a System Error go to "Troubleshooting" and
'display the ocurred fault code
'On Error GoTo Troubleshooting
'You want to show Sheet("X") first and then
'Deactivate ScreenUpdating
' 'Deactivate Alerts
' Application.DisplayAlerts = False
' Application.ScreenUpdating = False
' Application.UseSystemSeparators = False
'Display hidden Sheet "X", select cell "A1" and freeze screen
' ------------------------- NOT WORKING ---------------------
ActiveWorkbook.Sheets("X").Visible = xlSheetVisible
With ActiveWorkbook.Sheets("X")
Application.Goto .Range("A1")
ActiveWindow.FreezePanes = True
End With
'Deactivate Alerts
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.UseSystemSeparators = False
'Delete contents for each Sheet containing the name "Data"
'for the selected range
' ------------------------- NOT WORKING ---------------------
xSheetCount = ActiveWorkbook.Worksheets.Count
For zCt = 1 To xSheetCount '
If Left(Sheets(zCt).Name, 4) = "Data" Then
With ActiveSheet
.Range("B5:K90000").ClearContents
End With
End If
Next zCt
'Select the folder with the desired data to import
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Folder"
.ButtonName = "Import Data"
.InitialView = msoFileDialogViewList
If .Show = -1 Then xFolder = .SelectedItems(1)
If Right(xFolder, 1) <> "\" Then xFolder = xFolder & "\"
End With
'On error or no files found display the following
If xFolder = "" Then
MsgBox ("No files found or selected!")
Exit Sub
End If
Dim FS As Object
Dim Folder As Object
Dim myFile As Object
'Get the desired Textfiles in the selected Folder
Set FS = CreateObject("Scripting.FileSystemObject")
Set Folder = FS.Getfolder(xFolder)
For Each myFile In Folder.Files
If myFile.Name Like "*####-##-##*" Then
MsgBox (myFile.Name & " found!")
xFile = myFile.Name
If xFile <> "" Then
xCount = xCount + 1
xFiles.Add xFile, xFile
If xFile = "" Then Resume Next
End If
End If
Next myFile
'File processing
iCt = 1
Set Destbook = ThisWorkbook
MsgBox "xFiles count: " & xFiles.Count
If xFiles.Count > 0 Then
For aCt = 1 To xFiles.Count
Set Sourcebook = Workbooks.Open(xFolder & xFiles.Item(aCt), local:=True)
'Skip files with no current values greater than 2 A
xMax = Application.WorksheetFunction.Max(Range("C2:C90000"))
If xMax < 2 Then
GoTo ContinueLoop
End If
If InStr(1, ActiveSheet.Name, "Stufe", vbTextCompare) <> 0 Then
Columns("I:Y").Delete
Rows(1).Insert
Range("D1").Value = ActiveSheet.Name
xRow = Cells(Rows.Count, 1).End(xlUp).Row
ActiveSheet.Range("A1:J" & xRow).Copy
End If
ThisWorkbook.Sheets("Data (" + CStr(iCt) +")").Range("B3").PasteSpecial Paste:=xlPasteAll
Application.CutCopyMode = False
On Error Resume Next
On Error GoTo 0
iCt = iCt + 1
ContinueLoop:
Sourcebook.Close False
Next aCt
End If
'Just some formatting things...
' ------------------------- NOT WORKING ---------------------
xSheetCount = ActiveWorkbook.Worksheets.Count
For iCt = 1 To xSheetCount
If Left(Worksheets(iCt).Name, 4) = "Data" Then
With ActiveSheet.Range("A1:J" & xRow)
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
Range("B3:C3").Merge
Range("B3").Value = "Filename:"
Range("B3:K4").Font.Bold = True
Range("B4:K4").Borders.LineStyle = xlContinuous
End With
End If
Next iCt
'Delete sheet "Import data", hide sheet "X" and save file
'Sheets("Import data").Delete
ActiveWorkbook.Sheets("X").Visible = xlSheetVeryHidden
Application.DisplayAlerts = True
Application.ScreenUpdating = False
Application.UseSystemSeparators = True
'DestBook.SaveAs Filename:=CStr(Date) + "Analysis", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
'Display the occured error message and exit program
Troubleshooting:
Application.DisplayAlerts = True
Application.ScreenUpdating = True
If Err.Number <> 0 Then MsgBox "Troubleshooting: " & _
Err.Number & vbLf & Err.Description: Err.Clear
Exit Sub
End Sub

Optimize Excel VBA Macro for Copy-PasteValues

I'm new in Excel-VBA and I need to improve my macro performance. I have a macro that searches an excel, opens it, then goes through every sheet and copy-pastevalues for all cell with a specific color (yellow). Finally saves and closes the excel. In addition, excels sheets are locked and only those yellow cells are editable. This should be done for a list of excel that I indicate in a main template from where I call the macro. The problem is that it takes a lot of time and even gets blocked when the number of excels is more than 3.
I paste my code below and hope anyone can help. Thanks!
Sub Button1_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim filePath As String
Dim rng As Range
Dim cel As Range
Dim cartera As String
Dim plantilla As String
Dim wb As Workbook
Dim ws As Worksheet
Dim obj_Cell As Range
filePath = Application.ThisWorkbook.Path
Range("B9").Select
Set rng = Application.Range(Selection, Selection.End(xlDown))
For Each cel In rng.Cells
cartera = cel.Value
plantilla = cel.Offset(0, 1).Value
If cartera = vbNullString Or plantilla = vbNullString Then
GoTo Saltar
End If
Application.StatusBar = "Ejecutando Cartera: " & cartera & ", Plantilla: " & plantilla
Set wb = Workbooks.Open(filePath & "\" & cartera & "\" & plantilla, UpdateLinks:=3)
For Each ws In wb.Worksheets
If ws.Name <> "Index" And ws.Name <> "Instructions" And ws.Name <> "Glossary" Then
Worksheets(ws.Name).Activate
For Each obj_Cell In Range("A1:DW105")
With obj_Cell
If obj_Cell.Interior.Color = RGB(255, 255, 153) Then
obj_Cell.Select
If obj_Cell.MergeCells = True Then
obj_Cell.MergeArea.Select
End If
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=True, Transpose:=False
If obj_Cell.MergeCells = True Then
If obj_Cell.MergeArea(1).Value = vbNullString Then
obj_Cell.MergeArea.Cells(1, 1).Select
Selection.ClearContents
End If
Else
If obj_Cell.Value = vbNullString Then
obj_Cell.ClearContents
End If
End If
End If
End With
Next obj_Cell
Range("A1").Select
End If
Next ws
Sheets(1).Select
wb.Close SaveChanges:=True
Saltar:
Next cel
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.StatusBar = False
End Sub
Untested- just some "start" ideas for you to use (e.g. no selections, using arrays, fix With statement, no GoTo). I don't understand the logic behind clearing vbNullstring. If it is necessary adapt the code in your way.
I would also suggest opening files with displayalerts on because of few potential problems (e.g. "serious error occur last time file was opened" would hangs your macro)
Sub Button1_Click()
With Application
.ScreenUpdating = False
.StatusBar = True
End With
' If possible change this reference
' from active sheet to sheet's name/codename/index
Dim activeWs As Worksheet
Set activeWs = ActiveSheet
Dim filePath As String
filePath = Application.ThisWorkbook.Path
Dim wb As Workbook
Dim ws As Worksheet
Dim obj_Cell As Range
' range definition
' if lastRow not working change to yours xlDown
' if possible End(xlUp) method is more reliable
Dim rng As Range
Dim lastRw As Long
With activeWs
lastRw = .Cells(.Cells.Rows.Count, "B").End(xlUp).Row
Set rng = .Range("B9:B" & lastRw)
End With
' read whole ranges at once
' instead of offset it is possible also to read
' cartera and plantilla at the same time to 2Darray
Dim cartera As Variant
cartera = Application.Transpose(rng.Value2)
Dim plantilla As Variant
plantilla = Application.Transpose(rng.Offset(, 1).Value2)
' main loop
Dim i As Long
For i = 1 To UBound(cartera)
If cartera(i) <> vbNullString Or plantilla(i) <> vbNullString Then
Application.StatusBar = "Ejecutando Cartera: " & cartera(i) & ", Plantilla: " & plantilla(i)
Set wb = Workbooks.Open(filePath & "\" & cartera(i) & "\" & plantilla(i), UpdateLinks:=3)
For Each ws In wb.Worksheets
If ws.Name <> "Index" And ws.Name <> "Instructions" And ws.Name <> "Glossary" Then
For Each obj_Cell In ws.Range("A1:DW105")
With obj_Cell
If .Interior.Color = RGB(255, 255, 153) Then
.Value2 = .Value2
' I commented this part beacuse it does not make sense for me...
' If .MergeCells Then
' If .MergeArea(1).Value = vbNullString Then _
.MergeArea.Cells(1, 1).ClearContents
' Else
' If .Value = vbNullString Then .ClearContents
' End If
End If
End With
Next obj_Cell
End If
Next ws
' I would place diplayalerts off here because of potential problems
' with opening files
' if problem occurs it can macro hangs
Application.DisplayAlerts = False
wb.Close SaveChanges:=True
Application.DisplayAlerts = True
End If
Next i
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.StatusBar = False
End With
End Sub

Excel error message"one or more named invalid references"

I cannot find the named range or reference that is invalid, according to Excel. I checked my named ranges, including ranges within charts. The excel file contains a macro that creates a report that works fine when launched within the file itself. However, if I call that function from another workbook to run the report that is when I get the error message of invalid references. When going through the reports created both directly and indirectly they seem identical. Setting Application.DisplayAlerts = False does not work.
I tried using the code below from from Allen Wyatt to go through all reference and none refer to outside sheets nor contain any errors.
Sub CheckReferences()
' Check for possible missing or erroneous links in
' formulas and list possible errors in a summary sheet
Dim iSh As Integer
Dim sShName As String
Dim sht As Worksheet
Dim c, sChar As String
Dim rng As Range
Dim i As Integer, j As Integer
Dim wks As Worksheet
Dim sChr As String, addr As String
Dim sFormula As String, scVal As String
Dim lNewRow As Long
Dim vHeaders
vHeaders = Array("Sheet Name", "Cell", "Cell Value", "Formula")
'check if 'Summary' worksheet is in workbook
'and if so, delete it
With Application
.ScreenUpdating = False
.DisplayAlerts = False
.Calculation = xlCalculationManual
End With
For i = 1 To Worksheets.Count
If Worksheets(i).Name = "Summary" Then
Worksheets(i).Delete
End If
Next i
iSh = Worksheets.Count
'create a new summary sheet
Sheets.Add After:=Sheets(iSh)
Sheets(Sheets.Count).Name = "Summary"
With Sheets("Summary")
Range("A1:D1") = vHeaders
End With
lNewRow = 2
' this will not work if the sheet is protected,
' assume that sheet should not be changed; so ignore it
On Error Resume Next
For i = 1 To iSh
sShName = Worksheets(i).Name
Application.Goto Sheets(sShName).Cells(1, 1)
Set rng = Cells.SpecialCells(xlCellTypeFormulas, 23)
For Each c In rng
addr = c.Address
sFormula = c.Formula
scVal = c.Text
For j = 1 To Len(c.Formula)
sChr = Mid(c.Formula, j, 1)
If sChr = "[" Or sChr = "!" Or _
IsError(c) Then
'write values to summary sheet
With Sheets("Summary")
.Cells(lNewRow, 1) = sShName
.Cells(lNewRow, 2) = addr
.Cells(lNewRow, 3) = scVal
.Cells(lNewRow, 4) = "'" & sFormula
End With
lNewRow = lNewRow + 1
Exit For
End If
Next j
Next c
Next i
' housekeeping
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.Calculation = xlCalculationAutomatic
End With
' tidy up
Sheets("Summary").Select
Columns("A:D").EntireColumn.AutoFit
Range("A1:D1").Font.Bold = True
Range("A2").Select
End Sub

Excel TOC using vba - removed leading zeros

I used vba to create a TOC for my workbook, but the code formatted my wsname to a number format and removed the leading zeros. Is there a way to modify the code to include the leading zeros in the links?
For example, each of my worksheets is titled with a number beginning with a zero such as "0303855" etc. When I ran this code, my TOC list was numbers without the zero ("303855" etc).
I used the following code:
Sub CreateTOC()
Dim wsA As Worksheet
Dim ws As Worksheet
Dim wsTOC As Worksheet
Dim lRow As Long
Dim rngList As Range
Dim lCalc As Long
Dim strTOC As String
Dim strCell As String
lCalc = Application.Calculation
On Error GoTo errHandler
Application.EnableEvents = False
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
strTOC = "TOC"
strCell = "A1"
Set wsA = ActiveSheet
On Error Resume Next
Set wsTOC = Sheets(strTOC)
On Error GoTo errHandler
If wsTOC Is Nothing Then
Set wsTOC = Sheets.Add(Before:=Sheets(1))
wsTOC.Name = strTOC
Else
wsTOC.Cells.Clear
End If
With wsTOC
.Range("B1").Value = "Sheet Name"
lRow = 2
For Each ws In ActiveWorkbook.Worksheets
If ws.Visible = xlSheetVisible _
And ws.Name <> strTOC Then
.Cells(lRow, 2).Value = ws.Name
.Hyperlinks.Add _
Anchor:=.Cells(lRow, 2), _
Address:="", _
SubAddress:="'" & ws.Name _
& "'!" & strCell, _
ScreenTip:=ws.Name, _
TextToDisplay:=ws.Name
lRow = lRow + 1
End If
Next ws
Set rngList = .Cells(1, 2).CurrentRegion
rngList.EntireColumn.AutoFit
.Rows(1).Font.Bold = True
End With
Application.ScreenUpdating = True
wsTOC.Activate
wsTOC.Cells(1, 2).Activate
exitHandler:
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.Calculation = lCalc
Set rngList = Nothing
Set wsTOC = Nothing
Set ws = Nothing
Set wsA = Nothing
Exit Sub
errHandler:
MsgBox "Could not create list"
Resume exitHandler
End Sub

Generating a macro button with a macro

Using Excel 2013, I am looking to insert code into preexisting macro called "Rebuild_TOC" to generate a macro button on my "TOC" worksheet which calls "Repair_Back_To_TOC", a macro. I would like it to appear on my TOC at cells C2:E3, if possible, named "Rebuild Back to TOC Hyperlinks".
How would I go about accomplishing this with my current code?:
Sub Rebuild_TOC()
Dim wbBook As Workbook
Dim wsActive As Worksheet
Dim wsSheet As Worksheet
Dim lnRow As Long
Dim lnPages As Long
Dim lnCount As Long
Set wbBook = ActiveWorkbook
With Application
.DisplayAlerts = False
.ScreenUpdating = False
End With
' If the TOC sheet already exist delete it and add a new worksheet.
On Error Resume Next
Application.EnableEvents = False
With wbBook
.Worksheets("TOC").Delete
.Worksheets.Add Before:=.Worksheets(1)
End With
Application.EnableEvents = True
On Error GoTo 0
Set wsActive = wbBook.ActiveSheet
With wsActive
.Name = "TOC"
With.Range("A1:B1")
.Value = Array("Table of Contents", "Sheet # – # of Pages")
.Font.Bold = True
End With
End With
lnRow = 2
lnCount = 1
' Iterate through the worksheets in the workbook and create sheetnames, add hyperlink
' and count & write the running number of pages to be printed for each sheet on the TOC.
For Each wsSheet In wbBook.Worksheets
If wsSheet.Name <> wsActive.Name Then
wsSheet.Activate
With wsActive
.Hyperlinks.Add .Cells(lnRow, 1), "", _
SubAddress:= wsSheet.Name & "!A1", _
TextToDisplay:=wsSheet.Name
lnPages = wsSheet.PageSetup.Pages().Count
.Cells(lnRow, 2).Value = "‘" & lnCount & "-" & lnPages
End With
lnRow = lnRow + 1
lnCount = lnCount + 1
End If
Next wsSheet
wsActive.Activate
wsActive.Columns("A:B").EntireColumn.AutoFit
With Application
.DisplayAlerts = True
.ScreenUpdating = True
End With
End Sub

Resources