Type Mismatch Error VBA: Array referencing named ranges in Workbook - excel

SCOPE
Code below is attempting to grab all table objects, chart objects and range names on my workbook as an array, then the code creates a data validation column on a table which these arrays can then be referenced--so later I can use this table to auto generate a PowerPoint presentation.
PROBLEM
Code for grabbing tables and charts works great--getting type mismatch error when developing the portion of code for named ranges (please see further down for entire block of code/variables):
'if we have named ranges'
If ThisWorkbook.Names.Count > 0 Then
'grab each range
**For Each ExcRng In ThisWorkbook.Names** **'PROBLEM OCCURS HERE'**
'update count
ObjectArrayIndex = ObjectArrayIndex + 1
ReDim Preserve ObjectArray(ObjectArrayIndex)
'add the named range to array
ObjectArray(ObjectArrayIndex) = ExcRng.Name & "-" & xlSheet.Name & "-" & TypeName(ExcRng)
CODE
Sub GetTablesAndChartToExportTable()
Dim xlBook As Workbook
Dim xlSheet As Worksheet
Dim xlTable As ListObject
Dim xlTableColumn As ListColumn
Dim xlChartObject As ChartObject
Dim xlTableObject As ListObject
Dim ObjectArray() As String
Dim ObjectIndexArray As Integer
Dim ExcRng As Range
'set the book
Set xlBook = ThisWorkbook
'loop through each worksheet
For Each xlSheet In xlBook.Worksheets
'if we have charts
If xlSheet.ChartObjects.Count > 0 Then
'grab each chart name
For Each xlChartObject In xlSheet.ChartObjects
'update count
ObjectArrayIndex = ObjectArrayIndex + 1
ReDim Preserve ObjectArray(ObjectArrayIndex)
'add the chart object to array
ObjectArray(ObjectArrayIndex) = xlChartObject.Name & "-" & xlSheet.Name & "-" & TypeName(xlChartObject)
Next
End If
'if we have tables
If xlSheet.ListObjects.Count > 0 Then
'grab each table name
For Each xlTableObject In xlSheet.ListObjects
'update count
ObjectArrayIndex = ObjectArrayIndex + 1
ReDim Preserve ObjectArray(ObjectArrayIndex)
'add the table object to array
ObjectArray(ObjectArrayIndex) = xlTableObject.Name & "-" & xlSheet.Name & "-" & TypeName(xlTableObject)
Next
End If
'if we have named ranges'
If ThisWorkbook.Names.Count > 0 Then
'grab each range
For Each ExcRng In ThisWorkbook.Names
'update count
ObjectArrayIndex = ObjectArrayIndex + 1
ReDim Preserve ObjectArray(ObjectArrayIndex)
'add the named range to array
ObjectArray(ObjectArrayIndex) = ExcRng.Name & "-" & xlSheet.Name & "-" & TypeName(ExcRng)
Next
End If
Next
'grab sheet
Set xlSheet = xlBook.Worksheets("Export")
'grab table from sheet
Set xlTable = xlSheet.ListObjects("ExportToPowerPoint")
'grab object column from table
Set xlTableColumn = xlTable.ListColumns("Object")
'set the validation dropdown
With xlTableColumn.DataBodyRange.Validation
'delete old
.Delete
'add new data
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=Join(ObjectArray, ",")
'make sure it's a dropdown
.InCellDropdown = True
End With
End Sub
NOTICE
I am by no means very experienced in VBA, please, in your answer, include as much detail as possible

The For Each ExcRng In ThisWorkbook.Names is iterating through the collection ThisWorkbook.Names. Thus, the ExcRng should be of type Name.
To stay on the sure site, whenever iterating with For Each [x] In [y], declare the [x] as a variant. This will make sure it works, but it will take away intellisense and will be a bit "heavier".

Related

Excel file crashes and closes when I run the code, but results of the code who when I reopen the file

I am copying data under columns with matching headers between the source sheet and the destination sheet. Both the sheets are in the same excel file but they need to have a clarification number.
For example, one of the columns in the destination sheet has the the clarification number QM6754 and the row of data of QM6754. The source sheet also has the clarification number column but I dont want to copy it, I want to copy the other data in the row of this specific clarification number to the destination sheet that in one of its columns. this way the data isn't copied randomly and the entire row from each sheet relate to each other.
The code I used shows results(I modified it) but when I run it, the excel file shows (not responding) for about 3-4 minutes and then shutsdown or leaves a blank Excel sheet and VBA window. I close the excel file and reopen it and the data has been copied. The file is quite large and I have three pushbuttons that run this code for each sheet I want to copy data from. Three sheets with average of 3k-6k rows. But I cannot eliminate the rows.
The code runs but I would like to optimize of the way it runs because it isn't practical to run, close file and then open file again. Could the issue be with the For loop?
Sub CopyColumnData()
Dim wb As Workbook
Dim myworksheet As Variant
Dim workbookname As String
' DECLARE VARIABLES
Dim i As Integer ' Counter
Dim j As Integer ' Counter
Dim colsSrc As Integer ' PR Report: Source worksheet columns
Dim colsDest As Integer ' Open PR Data: Destination worksheet columns
Dim rowsSrc As Long ' Source worksheet rows
Dim WsSrc As Worksheet ' Source worksheet
Dim WsDest As Worksheet ' Destination worksheet
Dim ws1PRRow As Long, ws1EndRow As Long, ws2PRRow As Long, ws2EndRow As Long
Dim searchKey As String, foundKey As String
workbookname = ActiveWorkbook.Name
Set wb = ThisWorkbook
myworksheet = "Sheet 1 copied Data"
wb.Worksheets(myworksheet).Activate
' SET VARIABLES
' Source worksheet: Previous Report
Set WsSrc = wb.Worksheets(myworksheet)
Workbooks(workbookname).Sheets("Main Sheet").Activate
' Destination worksheet: Master Sheet
Set WsDest = Workbooks(workbookname).Sheets("Main Sheet")
'Adjust incase of change in column in both sheets
ws1ORNum = "K" 'Clarification Number
ws2ORNum = "K" 'Clarification Number
' Setting first and last row for the columns in both sheets
ws1PRRow = 3 'The row we want to start processing first
ws1EndRow = WsSrc.UsedRange.Rows(WsSrc.UsedRange.Rows.Count).Row
ws2PRRow = 3 'The row we want to start search first
ws2EndRow = WsDest.UsedRange.Rows(WsDest.UsedRange.Rows.Count).Row
For i = ws1PRRow To ws1EndRow ' first and last row
searchKey = WsSrc.Range(ws1ORNum & i)
'if we have a non blank search term then iterate through possible matches
If (searchKey <> "") Then
For j = ws2PRRow To ws2EndRow ' first and last row
foundKey = WsDest.Range(ws2ORNum & j)
' Copy result if there is a match between PR number and line in both sheets
If (searchKey = foundKey) Then
' Copying data where the rows match
WsDest.Range("AI" & j).Value = WsSrc.Range("A" & i).Value
WsDest.Range("AJ" & j).Value = WsSrc.Range("B" & i).Value
WsDest.Range("AK" & j).Value = WsSrc.Range("C" & i).Value
WsDest.Range("AL" & j).Value = WsSrc.Range("D" & i).Value
WsDest.Range("AM" & j).Value = WsSrc.Range("E" & i).Value
WsDest.Range("AN" & j).Value = WsSrc.Range("F" & i).Value
WsDest.Range("AO" & j).Value = WsSrc.Range("G" & i).Value
WsDest.Range("AP" & j).Value = WsSrc.Range("H" & i).Value
Exit For
End If
Next
End If
Next
'Close Initial PR Report file
wb.Save
wb.Close
'Pushbuttons are placed in Summary sheet
'position to Instruction worksheet
ActiveWorkbook.Worksheets("Summary").Select
ActiveWindow.ScrollColumn = 1
Range("A1").Select
ActiveWorkbook.Worksheets("Summary").Select
ActiveWindow.ScrollColumn = 1
Range("A1").Select
End Sub
To increase the speed and reliability, you will want to handle the copy/paste via array transfer instead of the Range.Copy method. Given your existing code, here's how a solution that should work for you:
Sub CopyColumnData()
'Source data info
Const sSrcSheet As String = "Sheet 1 copied Data"
Const sSrcClarCol As String = "K"
Const lSrcPRRow As Long = 3
'Destination data info
Const sDstSheet As String = "Main Sheet"
Const sDstClarCol As String = "K"
Const lDstPRRow As Long = 3
'Set variables based on source and destination
On Error Resume Next
Dim wbSrc As Workbook: Set wbSrc = ThisWorkbook
Dim wsSrc As Worksheet: Set wsSrc = wbSrc.Worksheets(sSrcSheet)
Dim wbDst As Workbook: Set wbDst = ActiveWorkbook
Dim wsDst As Worksheet: Set wsDst = wbDst.Worksheets(sDstSheet)
On Error GoTo 0
'Verify source and destination were found
If wsSrc Is Nothing Then
MsgBox "Worksheet """ & sSrcSheet & """ not found in " & wbSrc.Name
Exit Sub
End If
If wsDst Is Nothing Then
MsgBox "Worksheet """ & sDstSheet & """ not found in " & wbDst.Name
Exit Sub
End If
'Setup variables to handle Clarification Number matching and data transfer via array
Dim hDstClarNums As Object: Set hDstClarNums = CreateObject("Scripting.Dictionary") 'Clarification Number Matching
'Load Source data into array
Dim rSrcData As Range: Set rSrcData = wsSrc.Range(sSrcClarCol & lSrcPRRow, wsSrc.Cells(wsSrc.Rows.Count, sSrcClarCol).End(xlUp))
Dim aSrcClarNums() As Variant: aSrcClarNums = rSrcData.Value
Dim aSrcData() As Variant: aSrcData = Intersect(rSrcData.EntireRow, wsSrc.Columns("A:H")).Value 'Transfer data from columns A:H
'Prepare dest data array
Dim rDstData As Range: Set rDstData = wsDst.Range(sDstClarCol & lDstPRRow, wsDst.Cells(wsDst.Rows.Count, sDstClarCol).End(xlUp))
Dim aDstClarNums() As Variant: aDstClarNums = rDstData.Value
Dim aDstData() As Variant: aDstData = Intersect(rDstData.EntireRow, wsDst.Columns("AI:AP")).Value 'Destination will be into columns AI:AP
'Use dictionary to perform Clarification Number matching
Dim vClarNum As Variant
For Each vClarNum In aDstClarNums
If Not hDstClarNums.Exists(vClarNum) Then hDstClarNums.Add vClarNum, hDstClarNums.Count + 1
Next vClarNum
'Transfer data from source to destination using arrays
Dim i As Long, j As Long
For i = 1 To UBound(aSrcClarNums, 1)
For j = 1 To UBound(aSrcData, 2)
If hDstClarNums.Exists(aSrcClarNums(i, 1)) Then aDstData(hDstClarNums(aSrcClarNums(i, 1)), j) = aSrcData(i, j)
Next j
Next i
'Output to destination
Intersect(rDstData.EntireRow, wsDst.Columns("AI:AP")).Value = aDstData
'Save and close source workbook (uncomment next line if this is necessary)
'wbSrc.Close SaveChanges:=True
'Activate summary sheet, cell A1 in destination workbook (uncomment these lines if this is necessary)
'wbDst.Worksheets("Summary").Activate
'wbDst.Worksheets("Summary").Range("A1").Select
End Sub

Sum Values in different worksheets (same cell)

I have a workbook with multiple sheets ,the number of sheets can change for each project but they all end with PAF. The table is the same across all sheets as well as the cells.
I have a summary tab with the exact same table, I just need to sum it all up there, the table has at least 6 columns and 20 rows so each cell would need the same formula (basically) so I came up with the following but I'm getting an error. Any suggestions?
Sub SumPAF
Dim ws as Worksheet
Sheets("Summary PAF").Activate
For Each ws In ActiveWorkbook.Worksheets
If ws.Name Like "PAF" Then
Range("E10") = WorksheetFunction.Sum(Range("E10"))
End If
Next
End Sub
It's getting stuck in "For Each" saying that an Object is required...
I have commented the code so you should not have a problem understanding it.
Option Explicit
Sub SumPAF()
Dim ws As Worksheet
'~~> This will store the cell addresses
Dim sumFormula As String
'~~> Loop though each worksheet and check if it ends with PAF
'~~> and also to ingore summary worksheet
For Each ws In ActiveWorkbook.Worksheets
If UCase(ws.Name) Like "*PAF" And _
InStr(1, ws.Name, "Summary", vbTextCompare) = 0 Then _
sumFormula = sumFormula & "," & "'" & ws.Name & "'!E10"
'~~> or simply
'sumFormula = sumFormula & ",'" & ws.Name & "'!E10"
Next
'~~> Remove the intital ","
sumFormula = Mid(sumFormula, 2)
'~~> Insert the sum formula
If sumFormula <> "" Then _
Sheets("Summary PAF").Range("E10").Formula = "=SUM(" & sumFormula & ")"
End Sub
Here's a very simple and easy to understand program to illustrate how VBA can be used for loops over ranges. If you have any questions, feel free to ask:
Sub SumPAF()
'Save a reference to the Summary Sheet
Dim SummarySheet As Worksheet
Set SummarySheet = Sheets("Summary PAF")
'Save a reference to the Summary Table and decide the table dimensions
Dim SummaryTable As Range
Set SummaryTable = SummarySheet.Range("A1:F20")
'Create an array to save the sum values
Dim SumValues() As Double
ReDim SumValues(1 To SummaryTable.Rows.Count, 1 To SummaryTable.Columns.Count)
'Loop through the workbook sheets
Dim ws As Worksheet, TableRange As Range
For Each ws In ActiveWorkbook.Worksheets
'Find sheets ending in PAF other than the summary PAF
If ws.Name Like "*PAF" And Not ws.Name = SummarySheet.Name Then
'create a reference to a range on the sheet in the same place and dimensions as the summary table
Set TableRange = ws.Range(SummaryTable.Address)
'loop through the range, cell by cell
Dim i As Long, j As Long
For i = 1 To TableRange.Rows.Count
For j = 1 To TableRange.Columns.Count
'Sum each cell value into the array, where its cell address is the array coordinates.
SumValues(i, j) = SumValues(i, j) + TableRange.Cells(i, j).Value
Next j
Next i
End If
Next
'Output the array into the summary table
SummaryTable.Value = SumValues
End Sub

VBA Macro that removes duplicates based on column names

I am very new to Excel VBA I made this macro to remove duplicates based on column name "container". Now there are 2 columns in excel with the name "Container".
Sub Remove_DupContainerPOL()
'Removes Duplicate Containers
Dim whs As Worksheet
Dim lRow As Long, colNumber As Long
Dim colh As String
colh = "Container"
lRow = Range("A1").End(xlDown).Row
Set whs = Worksheets("POL")
colNumber = Application.Match(colh, whs.Range("A1:AAA1"), 0)
With whs.Range("A1:AAA" & lRow)
.RemoveDuplicates Columns:=colNumber, Header:=xlYes
End With
End Sub
Original Excel File
This is how the columns look like in the excel file. Now when I execute the macro it misbehaves somehow not sure the entire data in preceding rows get shuffled and generates the wrong output.
Is there any way that macro reads the 3 columns i.e. "Container" and only based on that removes duplicates?
Further, I am adding an explanation in detail.
Tab named Ocean which has 2 columns named Container! I coded in a way that the data in this ocean creates 2 new tabs named POL and POD and in that POL and POD tab I want to remove the duplicates based on the column named “Container” which is creating the wrong output.
Main Ocean tab where duplicate data.
POL Tab where Macro shuffled the data and gave wrong output
My complete macro codes below:
Sub Split_Ocean()
'------------------------------Filter on column Mode and split all Ocean moves into newsheet--------------------------
Application.AskToUpdateLinks = False
Dim wb As Workbook
' If the code is in the ActiveWorkbook you should use ThisWorkbook instead.
Set wb = ActiveWorkbook
' Delete Target Worksheet.
Dim FSht As Worksheet
On Error Resume Next
Set FSht = wb.Worksheets("Ocean")
If Err.Number = 0 Then
Application.DisplayAlerts = False
FSht.Delete
Application.DisplayAlerts = True
End If
On Error GoTo 0
' Define Target Worksheet.
Set FSht = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))
FSht.Name = "Ocean"
' Define Source Worksheet.
Dim Tsht As Worksheet
Set Tsht = wb.Worksheets("Main")
With Tsht
If Tsht.AutoFilterMode Then
Tsht.AutoFilterMode = False
End If
' 14 is column N
.Range("A1").AutoFilter Field:=14, Criteria1:="Ocean"
.AutoFilter.Range.Copy FSht.Range("A1")
End With
'-------------------------------------------------Endforabovecode---------------------
'Wait for 3 sec
Application.Wait (Now + TimeValue("0:00:03"))
'Create POL
Dim Source As Worksheet
Dim Destination As Worksheet
'Checking whether "POL" sheet already exists in the workbook
For Each Source In ThisWorkbook.Worksheets
If Source.Name = "POL" Then
MsgBox "POL sheet already exist"
Exit Sub
End If
Next
ActiveWorkbook.Worksheets("Ocean").Copy After:=Worksheets(Sheets.Count)
On Error Resume Next
ActiveSheet.Name = "POL"
'Autofit all contents in POL
ActiveWorkbook.Worksheets("POL").UsedRange.Columns.AutoFit
'Create POD & check whether "POD" sheet already exists in the workbook
For Each Source In ThisWorkbook.Worksheets
If Source.Name = "POD" Then
MsgBox "POD sheet already exist"
Exit Sub
End If
Next
ActiveWorkbook.Worksheets("Ocean").Copy After:=Worksheets(Sheets.Count)
On Error Resume Next
ActiveSheet.Name = "POD"
'Autofit all contents in POD
ActiveWorkbook.Worksheets("POD").UsedRange.Columns.AutoFit
Application.Wait (Now + TimeValue("0:00:02"))
ActiveWorkbook.Worksheets("Main").AutoFilterMode = False
End Sub
Sub Remove_DupContainerPOL()
'Removes Duplicate Containers
Dim whs As Worksheet
Dim lRow As Long, colNumber As Long
Dim colh As String
colh = "Container"
lRow = Range("A1").End(xlDown).Row
Set whs = Worksheets("POL")
colNumber = Application.Match(colh, whs.Range("A1:E1"), 0)
With whs.Range("A1:E1" & lRow)
.RemoveDuplicates Columns:=colNumber, Header:=xlYes
End With
End Sub
Sub Remove_DupContainerPOD()
'Removes Duplicate Containers
Dim whs As Worksheet
Dim lRow As Long, colNumber As Long
Dim colh As String
colh = "Container"
lRow = Range("A1").End(xlDown).Row
Set whs = Worksheets("POD")
colNumber = Application.Match(colh, whs.Range("A1:E1"), 0)
With whs.Range("A1:E1" & lRow)
.RemoveDuplicates Columns:=colNumber, Header:=xlYes
End With
End Sub
Main Ocean tab where duplicate data.
POL Tab where Macro shuffled the data and gave wrong output
With whs.Range("A1:E1" & lRow) .RemoveDuplicates should be With whs.Range("A1:N" & lRow) to cover all the columns (assuming N is last column). Or maybe just use With whs.UsedRange.

Excel Auto Change Sheet Name Based On Cells VBA

We have a workbook that needed to have the sheets change names every month and I decided to automate it for other employees. So after some research I found the best way to do it was to reference the names of cells. I needed it to start running on the 4th sheet and run through the second last sheet. I found some VBA code and edited it until I got to this point:
Sub RenameSheet()
Dim ShCnt As Integer 'count of sheets in workbook
Dim myarray() As String 'array of new worksheet names
Dim Month() As String 'mystery variable -- not used in this code
Dim i As Integer 'loop counter
Dim Lrow As Integer 'number of new worksheet names.
ThisWorkbook.Sheets("SETUP").Select 'select the sheet that has the list of new names
Lrow = Range("T1").End(xlDown).Row 'get range that contains new worksheet names
ShCnt = ThisWorkbook.Sheets.Count 'get number of worksheets in the workbook
ReDim myarray(1 To Lrow) 'resize array to match the number of new worksheet names
For i = 1 To UBound(myarray) 'loop through array of new sheet names
myarray(i) = Range("T" & i).Value 'insert new sheet name into array
Debug.Print Range("T" & i).Value 'show the new worksheet name in 'the Immediate window to be able to check that we're getting what we want
Next i 'end of loop
For i = 4 To ShCnt - 1 'loop through array of existing worksheets
Sheets(i).Name = myarray(i) 'rename each worksheet with the matching name from myarray
Next i 'end of loop
MsgBox "Sheets name has changed successfully" 'report success
End Sub
My issue is that I need the 4th sheet to start with the value in cell "T2". I have figured out that this section of code changed the starting point:
For i = 1 To UBound(myarray)
myarray(i) = Range("T" & i).Value
Debug.Print Range("T" & i).Value
Next i
When I replaced myarray(i) = Range("T" & i).Value with myarray(i) = Range("T2" & i).Value it started on cell T24 for some reason (which may have to do with the placement of my button?) and myarray(i) = Range("T" + 1 & i).Value doesn't work.
I also tried changing the For i = 1 To UBound(myarray) to For i = 2 To UBound(myarray) and that didn't work either.
Can someone please help me figure out how to get it so that the information in cell T2 ends up on the 4th sheet and goes from there? Thank you very much in advance.
I would suggest loop through worksheets in the workbook and use the loop counter to index into the range of names in column T:
Sub RenameSheet()
Dim ShCnt As Integer
Dim i As Integer
Dim ws_setup As Worksheet
Set ws_setup = ThisWorkbook.Worksheets("SETUP")
ShCnt = ThisWorkbook.Worksheets.Count
Const start_ws_index = 4
For i = start_ws_index To ShCnt - 1
ThisWorkbook.Worksheets(i).Name = _
ws_setup.Range("t2").Offset(i - start_ws_index, 0).Value
Next i
End Sub
Rename Sheets From List
In the current setup, it is assumed that the list is contiguous (no blanks), has at least two entries, and starts in cell T2, and that the 4th sheet is the first to be renamed.
The Code
Option Explicit
Sub renameSheets()
' Constants
Const wsName As String = "SETUP"
Const FirstCell As String = "T2"
Const FirstSheetIndex As Long = 4
' Workbook
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Array (at least two names)
Dim SheetNames As Variant
With wb.Worksheets(wsName)
SheetNames = .Range(FirstCell, .Range(FirstCell).End(xlDown))
End With
' Rename
Dim shOffset As Long: shOffset = FirstSheetIndex - 1
Dim i As Long
For i = 1 To UBound(SheetNames, 1)
wb.Sheets(i + shOffset).Name = SheetNames(i, 1)
Next i
' Inform
MsgBox "Sheet names changed successfully", vbInformation
End Sub

VBA to find all Named ranges as an Array and paste into a data validation column on a table

Currently I have code (below) that goes through and finds all charts and tables inside my workbook, takes their names as an array and pastes them onto a table as a data validation dropdown so that whomever is using the workbook can decide which tables and graphs to auto generate into a PowerPoint Presentation. Now I am trying to write code that also will do the same for named ranges. So not charts or tables. For some reason this seems to be way harder than I logically thought it would be. If anything I figured getting tables and charts to work would've been more of a headache but that has not been the case
Code and Picture of the aforementioned table are shown below
CODE:
Dim xlBook As Workbook
Dim xlSheet As Worksheet
Dim xlTable As ListObject
Dim xlTableColumn As ListColumn
Dim xlChartObject As ChartObject
Dim xlTableObject As ListObject
Dim ObjectArray() As String
Dim ObjectIndexArray As Integer
Dim ExcRng As Range
'set the book
Set xlBook = ThisWorkbook
'loop through each worksheet
For Each xlSheet In xlBook.Worksheets
'if we have charts
If xlSheet.ChartObjects.Count > 0 Then
'grab each chart name
For Each xlChartObject In xlSheet.ChartObjects
'update count
ObjectArrayIndex = ObjectArrayIndex + 1
ReDim Preserve ObjectArray(ObjectArrayIndex)
'add the chart object to array
ObjectArray(ObjectArrayIndex) = xlChartObject.Name & "-" & xlSheet.Name & "-" & TypeName(xlChartObject)
Next
End If
'if we have tables
If xlSheet.ListObjects.Count > 0 Then
'grab each table name
For Each xlTableObject In xlSheet.ListObjects
'update count
ObjectArrayIndex = ObjectArrayIndex + 1
ReDim Preserve ObjectArray(ObjectArrayIndex)
'add the table object to array
ObjectArray(ObjectArrayIndex) = xlTableObject.Name & "-" & xlSheet.Name & "-" & TypeName(xlTableObject)
Next
End If
Next
'grab sheet
Set xlSheet = xlBook.Worksheets("Export")
'grab table from sheet
Set xlTable = xlSheet.ListObjects("ExportToPowerPoint")
'grab object column from table
Set xlTableColumn = xlTable.ListColumns("Object")
'set the validation dropdown
With xlTableColumn.DataBodyRange.Validation
'delete old
.Delete
'add new data
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=Join(ObjectArray, ",")
'make sure it's a dropdown
.InCellDropdown = True
End With
PICTURE OF TABLE
As you can see from the picture; column A is where I have the references going. And as you can see the one chart and table that I have named so far for my workbook are showing up fine--so my code so far for Graphs and Tables seems to be working great. I now just need it to also populate named ranges on that same column A
ThisWorkbook.Names contains a reference to all the Names in the Workbook including Named Ranges.
I wrote a function to add the Named Ranges to an array.
Code
Function GetNamedRanges(SheetName As String) As Variant()
Dim Results As Variant
ReDim Results(1 To ThisWorkbook.Names.Count)
Dim Count As Long
Dim Name As Name
Dim Target As Range
For Each Name In ThisWorkbook.Names
On Error Resume Next
Set Target = Name.RefersToRange
If Err.Number = 0 Then
If Target.Parent.Name = SheetName Or Len(SheetName) = 0 Then
Count = Count + 1
Set Results(Count) = Target
On Error GoTo 0
End If
End If
Next
ReDim Preserve Results(1 To Count)
GetNamedRanges = Results
End Function
Usage
AllNames = GetNamedRanges
Sheet1Names = GetNamedRanges(Sheet1.Name)

Resources