我正在开发一个Excel VBA项目。在Sheet1中,我有一个表,每行有3个命令按钮。在这个表之外,我有另一个名为“cbSwap”的命令按钮。当我单击此按钮时,它会打开一个用户表单。此用户表单有2个文本框和一个按钮。用户表单从两个文本框中获取两个值,并将它们传输到名为SwapTwoRange的函数。此函数获取值,将它们用作Excel范围名称。这是功能:
Function SwapTwoRange(val1 As String, val2 As String)
Dim arr1 As Variant, arr2 As Variant
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = ThisWorkbook.Sheets("Sheet1").Range("row" & val1)
Set Rng2 = ThisWorkbook.Sheets("Sheet1").Range("row" & val2)
Application.ScreenUpdating = False
arr1 = Rng1.Value
arr2 = Rng2.Value
Rng1.Value = arr2
Rng2.Value = arr1
Application.ScreenUpdating = True
'No problem occured until here.
If (WorksheetFunction.CountA(Rng1) = 0) Then
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbStartRow" & val1).Object.Enabled = True
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbEndRow" & val1).Object.Enabled = False
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbClearRow" & val1).Object.Enabled = False
Else
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbStartRow" & val1).Object.Enabled = False
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbEndRow" & val1).Object.Enabled = True
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbClearRow" & val1).Object.Enabled = True
End If
If (WorksheetFunction.CountA(Rng2) = 0) Then
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbStartRow" & val2).Object.Enabled = True
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbEndRow" & val2).Object.Enabled = False
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbClearRow" & val2).Object.Enabled = False
Else
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbStartRow" & val2).Object.Enabled = False
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbEndRow" & val2).Object.Enabled = True
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbClearRow" & val2).Object.Enabled = True
End If
End Function
cbStartRow , cbEndRow 和 cbClearRow 是Sheet1中表行中的命令按钮。当if块执行时,它们看起来像我想要的那样启用/禁用。但是当我选择(例如)禁用命令按钮并查看其属性时,其已启用属性为 True 。该程序不能按我的意愿工作。我必须使用输入到文本框的值来引用命令按钮名称(例如,如果textbox1的值为“1”,则第一个if-else块将更改cbStartRow1,cbEndRow1和cbClearRow1的Enabled属性。)
如果没有这个问题怎么办呢?我在过去8天一直在互联网论坛上寻找解决方案,但我找不到正确的解决方案。请帮忙。不管怎样,谢谢。
答案 0 :(得分:1)
我只使用OLEObject.Object
第三方ActiveX控件,而VBA无法知道属性在哪里。
那么,请您尝试参考OLEObject
而不是OLEObject.Object
。然后,Enabled
属性实际上属于OLEObject
- 您可以查看here。
您的代码将是,例如:
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbStartRow" & val1).Enabled = True
不
ThisWorkbook.Sheets("Sheet1").OLEObjects("cbStartRow" & val1).Object.Enabled = True
您可以使用较小的示例尝试此方法。只需创建一个新的工作簿并插入一个按钮,然后将其放在Sheet1
的代码模块中。然后运行Test1
:
Option Explicit
Sub Test1()
Dim obj As OLEObject
Set obj = ThisWorkbook.Worksheets("Sheet1").OLEObjects(1)
obj.Enabled = True
Debug.Print obj.Enabled
obj.Enabled = False
Debug.Print obj.Enabled
obj.Enabled = True
Debug.Print obj.Enabled
End Sub
将输出:
True
False
True
然后运行Test2
:
Sub Test2()
Dim obj As OLEObject
Set obj = ThisWorkbook.Worksheets("Sheet1").OLEObjects(1)
obj.Object.Enabled = True
Debug.Print obj.Enabled
obj.Object.Enabled = False
Debug.Print obj.Enabled
obj.Object.Enabled = True
Debug.Print obj.Enabled
End Sub
将输出:
True
True
True