【发布时间】:2020-12-22 17:46:45
【问题描述】:
范围
下面的代码试图将我的工作簿上的所有表格对象、图表对象和范围名称作为一个数组获取,然后代码在表格上创建一个数据验证列,然后可以引用这些数组 - 这样以后我就可以使用此表格可自动生成 PowerPoint 演示文稿。
问题
用于抓取表格和图表的代码效果很好——在为命名范围开发代码部分时出现类型不匹配错误(请进一步查看整个代码/变量块):
'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)
代码
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
通知
我在 VBA 方面并不是很有经验,请在您的回答中包含尽可能多的细节
【问题讨论】:
-
请不要让我们找出哪一行错误。
-
@Vityata For Each ExcRng In ThisWorkbook.Names -- 我在旁边写了
-
试试
Dim ExcRng As Variant而不是Dim ExcRng As Range -
酷!尝试在单独的问题中重写代码,使用尽可能少的行以复制错误。真的,而不是 20+,只尝试验证和分配
ObjectArray。代码应该能够编译。祝你好运! -
Join(ObjectArray, ",")不会在连接的字符串中添加前导或尾随"。您需要添加这些
标签: excel vba type-mismatch