【发布时间】:2016-06-29 23:37:47
【问题描述】:
我正在使用 Excel 并希望根据单元格地址(例如 A3)获取表格的名称,该单元格不会移动。我将如何在 Excel 的 VBA 中说明这一点?
我的计划是编写代码,将数据验证从我的维护选项卡上的一个表的一行复制到我的工作簿每个选项卡上的单个表(减去我的“TOC”和“数据”选项卡)。每个选项卡都是“模板”工作表的副本(减去“TOC”、“数据”和“模板(维护)”工作表)。工作表“data”、“TEMPLATE”和“TEMPLATE (Maint.)”可能隐藏也可能不隐藏。
我的“Copy_Data_Validations”子代码如下:
Dim TotalSheets As Integer
Dim p As Integer
Dim iAnswer As VbMsgBoxResult
With Application
.DisplayAlerts = False
.ScreenUpdating = False
End With
'
' Move sheet "TOC" to the begining of the workbook.
'
Sheets("TOC").Move Before:=Sheets(1)
'
' Move sheet "data" to be the second sheet in the workbook.
'
Sheets("data").Move Before:=Sheets(2)
iAnswer = MsgBox("You are about to copy data validations!", vbOKCancel + vbExclamation _
+ vbDefaultButton2 + vbMsgBoxSetForeground, "Copying Data Valadations")
For TotalSheets = 1 To Sheets.Count
For p = 3 To Sheets.Count - 2
'
' If the answer is Yes, then copy data validations from "TEMPLATE (Maint.) to all other.
' sheets minus the "TOC" sheet and the "data" sheet.
'
If iAnswer = vbYes Then
If UCase$(Sheets(p).Name) <> "TOC" And UCase$(Sheets(p).Name) <> "data" Then
' This chunk of code should copy only the data validations
' of "Table1_1" (A4:AO4) from the maintenance tab to all
' rows of a single table on each worksheet (minus the
' "TOC", "data", & the "TEMPLATE (Maint.)" worksheets.
' This is the section of code I am looking for unless
' someone has something better they can come up with.
Selection.PasteSpecial Paste:=xlPasteValidation, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End If
'
' If the answer is Cancel, then cancels.
'
ElseIf iAnswer = vbCancel Then
' Add an exit here.
End If
With Application
.DisplayAlerts = True
.ScreenUpdating = True
End With
【问题讨论】:
-
Debug.Print Range("A3").ListObject.Name如果单元格不是表格的一部分,则会出错 -
这个问题有点模棱两可:例如如果 Cell ($A$3) 存在于 3 个 Worksheets 中,那么 VBA 函数应该返回哪个名称?顺便说一句,下面给出的解决方案意味着传递范围对象(这意味着父工作表),而不是像问题中所述的单元格地址。最好的问候,
-
我已更新问题以包含更多上下文,以便获得更清晰的答案。
-
您的问题仍然模棱两可,因为通过引用 Cell($A$3) 您已经暗示了它所在的工作表,因此您应该已经将该信息作为设置代码引用 Cell( 3 美元)。否则,将我在每个感兴趣的工作表中显示的工作表函数放入 VBA 中引用它(尽管这似乎是一个奇怪的解决方案)。最好的问候,
-
进一步澄清,我希望我比昨天的紧急工作做得更好,感觉不舒服,不得不赶回家。如果还有什么解释不够清楚,请告诉我。