我想根据表格的第一个和最后一个单元格在名称管理器中创建一个新条目。
我在我的宏中为当前工作表编写了这个硬编码,但是我会有很多不同大小的表格的工作表。
ActiveWorkbook.Names.Add Name:="TitleRegion1.a6.h48.4", RefersToR1C1:= "=pw!R142C1"
以下是我的情景:
我的工作表有一个表 - 表3,带有标题,跨越单元格A6到H49 我希望我的条目名为“TitleRegion1.a6.h49.4”
这些是我的变数。
TitleRegion = just a string,
1 = refers to the 1st table in the current worksheet,
a6 = start cell of table,
h49 = end cell of table,
worksheet 4 in workbook
这是使用Record Macro
的宏Sub Macro1()
Range("Table3[[#Headers],[Data Source]]").Select
ActiveWorkbook.Names.Add Name:="TitleRegion1.a6.h48.4", RefersToR1C1:= _
"=Table3[[#Headers],[Data Source]]"
End Sub`
[数据源] - 是a6的值 我不知道从哪里开始?我是Excel VBA编程的新手。
答案 0 :(得分:0)
您可以尝试下面的代码(不要使用工作文件,直到您看到它如何工作)
这就是它的作用:
Excel将在创建表时根据表名
自动生成新名称以下是代码(已更新):
Option Explicit
Sub makeTables()
Dim excludedSheets As String, sh As Worksheet, tbl As ListObject, i As Long
Dim tblRngList As Object, headerList As Object, indx As Long, rng As String
Set tblRngList = CreateObject("Scripting.Dictionary")
Set headerList = CreateObject("Scripting.Dictionary")
With tblRngList
.Add Key:=1, Item:="A6:H49" 'Sheet 1: Key:=1 -> sheet index
.Add Key:=2, Item:="A6:H22" 'Sheet 2: "A6:H22" -> Tbl region on Sheet2
.Add Key:=3, Item:="" 'Sheet 3: No table
End With
With headerList
.Add Key:=1, Item:="Header 1" 'Headers must be unique
.Add Key:=2, Item:="Header 2"
.Add Key:=3, Item:="Header 3"
.Add Key:=4, Item:="Header 4"
.Add Key:=5, Item:="Header 5"
.Add Key:=6, Item:="Header 6"
.Add Key:=7, Item:="Header 7"
.Add Key:=8, Item:="Header 8" 'Should match total cols defined in ranges
End With '"A6:H49" = 8 columns
With ActiveWorkbook 'Current Excel file
For Each sh In .Worksheets 'Iterate through all sheets of current file
With sh 'Current sheet: Sheet1, Sheet2, Sheet3
indx = .Index 'Current sheet index: 1, 2, 3
rng = tblRngList(indx) 'Current table range: "A6:H49", "A6:H22", ""
If Len(rng) > 0 Then 'If tbl rng is not empty ("")
If .ListObjects.Count > 0 Then 'If any previous tables exist
For Each tbl In sh.ListObjects 'Go through each one
tbl.Delete 'and delete it
Next
End If
'Create table ---------------------------------------------------
Set tbl = .ListObjects.Add(xlSrcRange, sh.Range(rng), , _
xlYes, , "TableStyleMedium5")
'Set Table name -------------------------------------------------
tbl.Name = "Title" & .ListObjects.Count & "." & _
tblRngList(indx) & "." & indx
'Set Headers ----------------------------------------------------
With tbl
For i = 1 To .HeaderRowRange.Count
.HeaderRowRange(i) = headerList(i)
Next
End With
End If
End With
Next
End With
End Sub
在一个包含3个默认工作表的新文件中,它将在Sheet1上创建一个表,在Sheet2上创建一个
如果超过3张,请使用以下行添加更多项目:
.Add Key:=7, Item:="A1:Z999"
其中Key是工作表的索引,item是该工作表上表格的范围
您可以更改" TableStyleMedium5"来自"表工具"的任何风格 - > "表样式"部分
将鼠标悬停在任何可用样式上以查看其名称(从名称中删除所有空格):
运行后,检查名称管理器以查找与此类似的列表(取决于排除的表格)