此代码有效。
Sub test()
Dim Rng1 As Range, Rng2 As Range
Dim ws1 As Worksheet, WS2 As Worksheet, i As Long
Set ws1 = ThisWorkbook.Worksheets("Test Summary")
Set Rng1 = ws1.Range("E2")
Set WS2 = ThisWorkbook.Worksheets("Examples")
Set Rng2 = WS2.Range("F2")
' Clear original data on Summary
i = 0
Do Until IsEmpty(Rng1.Offset(i, 0))
Rng1.Offset(i, 0).EntireRow.ClearContents
i = i + 1
Loop
i = 0
Do Until IsEmpty(Rng2.Offset(0, i))
If Rng2.Value <> "" Then
Rng1.Offset(0, 0).Formula = "='" & WS2.Name & "'!" & Rng2.Cells([7], [1]).Address 'Project
Rng1.Offset(0, 1).Formula = "='" & WS2.Name & "'!" & Rng2.Cells([9], [1]).Address 'Model
Rng1.Offset(0, 2).Formula = "='" & WS2.Name & "'!" & Rng2.Cells([10], [1]).Address 'ID`
Set Rng2 = Rng2.Offset(0, i + 1)
End If
Set Rng1 = Rng1.Offset(1, 0) ' Move to next row to check
Loop
i = 0
' Clean up
Set Rng1 = Nothing
Set ws1 = Nothing
Set Rng2 = Nothing
Set WS2 = Nothing
End Sub
当我尝试以编程方式添加按钮来触发宏时,它显示:
运行时错误“13”,类型不匹配
这是创建按钮和分配宏的代码。
Sub CommandButton_Click()
Dim b As Button
Dim ws10 As Worksheet
Set ws10 = ThisWorkbook.Worksheets("Test Summary")
Set b = ws10.Buttons.Add(200, 5, 80, 18.75) ' left, top, width, height
b.OnAction = "test" ' a sub name in module
b.Characters.Text = "Refresh" ' text on the button
End Sub
宏和按钮的代码位于不同的模块中。
按钮是一次性的东西。
我尝试手动添加按钮并分配宏。
同样的错误发生在:
Rng1.Offset(0, 0).Formula = "='" & WS2.Name & "'!" & Rng2.Cells([7], [1]).Address 'Project
您当前的
Sub CommandButton_Click()
存在一些问题
ws10.Buttons.Add(200, 5, 80, 18.75)
- 为什么每次点击都会创建一个新按钮?b.OnAction =
- 这是 C# 代码,而不是 VBA这个简单的代码应该足够了:
Sub CommandButton_Click()
Call test
End Sub