【发布时间】:2012-01-08 09:17:12
【问题描述】:
我想通过 VBA 代码在单元格中放置一个命令按钮。说位置 B3。我为此使用了宏记录器,但它给了我按钮的顶部底部值。我不希望那样,因为如果我将我的代码带到其他具有其他屏幕分辨率的计算机上,代码将会失败。单元格位置(例如 B3)将是一个绝对位置。
你能给我建议一个方法吗?
P.S 它是一个 activeX 按钮
谢谢
【问题讨论】:
我想通过 VBA 代码在单元格中放置一个命令按钮。说位置 B3。我为此使用了宏记录器,但它给了我按钮的顶部底部值。我不希望那样,因为如果我将我的代码带到其他具有其他屏幕分辨率的计算机上,代码将会失败。单元格位置(例如 B3)将是一个绝对位置。
你能给我建议一个方法吗?
P.S 它是一个 activeX 按钮
谢谢
【问题讨论】:
“将按钮放入单元格”的替代方法
使单元格选择直接执行代码,使用工作表事件:Worksheet_SelectionChange。将代码放在特定工作表的模块中。根据需要对单元格进行颜色/边框/文本。任何计算机或屏幕上的一个单元格就是一个单元格。当用户单击短标签/描述时,我使用它来引用加载到用户表单中的帮助,从帮助表上查找。使用单元格/按钮可以避免 IT 对 Active-X 对象的投诉。
需要考虑的事情,示例代码如下:
Select Case,即使您只有一个单元格/按钮。这简化了稍后添加单元格/按钮的路径Target.Address 返回整个范围,而不仅仅是一个单元格。如果您的Select Case 指的是Target 左上角单元格的地址,则可以避免此问题。Target.Cells(1,1).Address
MergeArea.Address(MergeArea 不适用于合并单元格[仅适用于单个单元格];它返回单元格所在的合并范围。*示例代码*
'How to Make Cells into Buttons that execute code
' place code in the specific Worksheet module of interest
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' in this example, I create named ranges on the spreadsheet '
' [complicated names, here, so you can read what's what]:
' one cell: "Button_OneCellNameRange"
' one set of merged cells: "Button_MergedCellNameRange"
' [the reference is the top-left cell, only]
' a VBA created cell/button location [not very useful for later sheet edits]
Dim myVBACellButton As Range
Set myVBACellButton = Range("B2")
Debug.Print "Target Address: " & Target.Address
'merged cells will return a range: eg "$A$1:$D$3"
Debug.Print "Target.Cells(1,1).Address: " & Target.Cells(1, 1).Address
'merged cells will return the top left cell, which would match
' a named reference to a merged cell
Select Case Target.Cells(1, 1).Address
'if you have merged cells, you must use the ".cells(1,1).address"
' and not just Target.Address
Case Is = "$A$1"
MsgBox "Hello from: Click on A1"
Case Is = myVBACellButton.Address
MsgBox "Hello from: Click on B2, a VBA referenced cell/button"
' "myCellButton" defined as range in VBA
'using a range named on the spreadsheet itself ...
' named ranges allow one to move the cell/button freely,
' without VBA worries
Case Range("Button_OneCellNameRange").Address
MsgBox "Hello From: Button Click on Button_OneCellNameRange"
Case Range("Button_MergedCellNamedRange").Address
'note that the address for merged cells is ONE CELL, the top left
MsgBox _
"Hello from: Button_MergedCellNamedRange.Address: " _
& Range("Button_MergedCellNamedRange").Address _
Case Else ' normally you wouldn't be using this, for buttons
MsgBox "NOT BUTTONS"
End Select
End Sub
【讨论】:
您不能将任何对象“放入”单元格中,只能放在其上方。您可以将按钮的 Left 和 Top 属性设置为 Cell 的 Left/Top。
Sub Tester()
Dim rng As Range
Set rng = ActiveSheet.Range("B3")
With ActiveSheet.OLEObjects("CommandButton1")
.Top = rng.Top
.Left = rng.Left
.Width = rng.Width
.Height = rng.RowHeight
End With
End Sub
【讨论】: