根据单元格值将标题分配给动态表单控件按钮

Assigning captions to dynamic form controls buttons based on cell value

我是 Excel VBA 的新手,所以如果描述含糊不清,我提前表示歉意。 我有一个代码,它在 "Demand Overview" 工作表中插入 W 列一定数量的产品名称("Product X"、"Product Y" 等....产品数量从 1 动态变化到 100),始终从单元格 W2 开始,并且始终在每个产品之间跳过一个单元格(例如产品 X 在 W2 中,产品 Y 在 W4 中等) 我想在 VBA 中编写的代码是为每个产品名称创建一个表单控制按钮,并将其标题更改为 W 列中的产品名称。 我可以编写代码来动态创建与 W 列中的产品名称一样多的表单控制按钮,但是,我很难为它们分配标题,因为我总是收到错误消息:"Unable to get the Buttons property of the Worksheet class"

分配逻辑是按钮 1 将获得位于 W2 的产品名称,按钮 2 将获得位于 W4 的产品名称等。

非常感谢任何帮助! 提前致谢!

Sub AddInfo()


Dim butn As Button
Dim rng As Range
Dim trial As Range
Dim i As Integer

Sheets("Demand Overview").Select
Set rng = ActiveSheet.Range("S:S")
For Each trial In ActiveSheet.Range("W:W")

 If trial.Value <> "" Then Set butn = ActiveSheet.Buttons.Add(rng.Left, 
 trial.Top, 150, 26)

Next trial

'the code works until this point

With ActiveSheet
For i = 1 To 100
.Buttons("Button" & i).Caption = Range("W" & 2 * i)
 Next i
 End With

 End Sub

试试这个。认为在创建按钮时引用按钮更有意义,这样您就知道自己引用了正确的按钮。

Sub AddInfo()

Dim butn As Button
Dim rng As Range
Dim trial As Range
Dim i As Long

With Sheets("Demand Overview")
    Set rng = .Range("S:S")
    For Each trial In .Range("W:W")
        If trial.Value <> "" Then
            Set butn = .Buttons.Add(rng.Left, trial.Top, 150, 26)
            i = i + 1
            butn.Caption = .Range("W" & 2 * i).Value
        End If
    Next trial
End With

End Sub

顺便说一句,我不会遍历整个 W,找到最后一行并将循环限制在必要的范围内,而不是所有的百万行。