我已经使用vba代码在A列的控制按钮中添加了一个新行。
代码工作正常,但有一个小问题。
我正在尝试在复制期间更改按钮名称属性,但我不知道该怎么做?
例如,我正在复制一个名为"验证"的按钮,当它被复制到下一行时我想将按钮的Name属性(而不是按钮文本)更改为&#34 ; validate1"
你能告诉我怎么做吗?Dim Lr As Integer
Dim newLr As Integer
Dim lim, rng, sht, btn As String
Lr = Range("B" & Rows.Count).End(xlUp).Row 'Searching last row in column A
newLr = Lr + 1
lim = "B" & newLr & ":" + "D" & newLr
rng = "A" & newLr
Rows(Lr).Copy
Rows(newLr).Insert
'Range(lim).ClearContents
sht = ActiveSheet.Name
btn = "validate" & newLr
Application.ScreenUpdating = False
Sheets(sht).Shapes("validate").Copy
Sheets(sht).Activate
Sheets(sht).Range(rng).Select
Sheets(sht).Paste
Sheets(sht).Shapes("validate").Select
Selection.Characters.Text = btn
Application.ScreenUpdating = True
图片链接: https://ibb.co/c0rFfv
答案 0 :(得分:1)
粘贴形状后,只需编写下面的代码即可。
Sheets(sht).Shapes(.Shapes.Count).Name = btn
因为当您添加新形状时,它具有最高的索引。所以,如果你
通过.Shapes.Count
找到最高的索引形状,然后您可以轻松地重命名它。
以及基于VBA最佳实践的其他一些建议:
1 - 始终使用明确的选项
因为如果您使用它,您会看到未定义"lim,rng,sht"
个变量。 Commas = ",'
不足以定义所有变量。您需要逐个单独声明它们。因此,而不是Dim lim, rng, sht, btn As String
使用Dim lim as String, rng as String, sht as String, btn As String
2 - 使用Long而不是Integer
因为Excel可能需要您的Integer to Long才能在较新版本的Excel中运行代码。您可以通过将变量定义为Long而不是Integer来简单地避免它。
3 - 从不假设工作表
不要依赖ActiveWorkbook或ActiveSheet,因为它们可能会被更改 由用户。
最佳做法是始终确定代码所涉及的工作表:
所以在你的例子中:
Dim wb as Workbook, ws as Worksheet
Set wb = ThisWorkbook
Set ws = wb.Sheet("Sheet1")
Lr = ws.Range("B" & Rows.Count).End(xlUp).Row
这种做法绝不会误导你。
4 - 避免使用选择或激活
.Select()很慢
.Select()是不守规矩的
.Select()将触发侦听器
5 - 使用描述性变量命名
代码中的描述性名称和结构有助于使注释变得不必要。
因此,您的代码将以这种方式更加清晰和高效:
Option Explicit
Application.ScreenUpdating = False
'It's better to switch off properties from starting of your macro
Dim wb as Workbook, ws as Worksheet
Dim Lr As Long
Dim newLr As Long
Dim sht as String, btn As String
Dim lim as Range, rng as Range 'Using these ones directly as a Range is better idea.
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")
Lr = ws.Range("B" & Rows.Count).End(xlUp).Row 'Searching last row in column A
'==> if you would like to count rows in A, then change your code. Now it's looking for "B".
newLr = Lr + 1
set lim = ws.Range("B" & newLr & ":" + "D" & newLr)
set rng = ws.Range("A" & newLr)
ws.Rows(Lr).Copy
ws.Rows(newLr).Insert
'Range(lim).ClearContents
sht = ws.Name
btn = "vaalidate" & newLr
With Sheets(sht)
.Shapes("validate").Copy
.rng.Paste
.Shapes(.Shapes.Count).Name = btn
End With
Application.ScreenUpdating = True
答案 1 :(得分:1)
无需使用Sheets(sht).Activate
和Sheets(sht).Range(rng).Select
它只会减慢代码运行时间,而是使用完全限定的Shapes
和Worksheets
,如下面的代码所示:
With Sheets(sht)
.Shapes("validate").Copy
.Paste
.Shapes(.Shapes.Count).Name = btn
End With
答案 2 :(得分:0)
在Selection.Characters.Text = btn
行之后,添加Selection.Name = btn
。