我有一张带有组合框的纸张。在组合框的左侧有一列,用户可以使用" X"标记位置。如果它右边的组合框应该做的东西(填充自动从动态范围取的值)。我正在考虑这样的事情但是没有让它成功:
Dim ComBx As ComboBox
Dim ws2 As Worksheet
Set ws2 = ActiveWorkbook.Worksheets("Tool")
For Each ComBx In ws2.ComboBox
If ComBx.Offset(0, -1).Value = "X" Then
With ComBx
'do stuff
End With
End If
Next ComBx
任何想法如何参考组合框的位置?我必须为复选框做类似的事情,它工作得很好,但这让我望而却步。
答案 0 :(得分:1)
如果您的组合框类型为Active-X
,请尝试以下代码。
ComBx.TopLeftCell.Offset(, -1).Value
返回位于组合框所在单元格左侧一列的单元格值。
注意:除此之外,您的代码中有错字,您定义并设置ComBx
,然后使用If CmBx.Offset(0, -1).Value = "X" Then
并且以Next CmBx
结束 - 这甚至不应该编译。
<强>代码强>
Option Explicit
Sub CmbBoxPosition()
Dim ComBx As OLEObject
Dim ws2 As Worksheet
Set ws2 = ActiveWorkbook.Worksheets("Tool")
For Each ComBx In ws2.OLEObjects
If ComBx.progID Like "Forms.ComboBox.1" Then
' for DEBUG Only
Debug.Print ComBx.Name & " located at " & ComBx.TopLeftCell.Address(False, False, xlA1)
If ComBx.TopLeftCell.Offset(, -1).Value = "X" Then
With ComBx
' the rest of your code goes here
End With
End If
End If
Next ComBx
End Sub
答案 1 :(得分:0)
如果您使用的是ActiveX组合框,那么您可以运行此示例以查看所有组合框的'TopLeftCell'值(或其中的任何偏移量)只是为了确定您正在查看正确的组合框。
Sub GetCombos()
Dim shp As Shape
Dim ws2 As Worksheet
Dim cel As Range
Set ws2 = ActiveWorkbook.Worksheets("Tool")
For Each shp In ws2.Shapes
If shp.FormControlType = xlDropDown Then
Set cel = shp.TopLeftCell.Offset(0, -1)
If cel.Value = "X" Then
Debug.Print "cell at row=" & cel.Row & " column=" & cel.Column & " has an X in it"
' do stuff
End If
End If
Next
End Sub
如果它不正确,您可以将shp.TopLeftCell.Offset(x,y)
的x和y值更改为正确的偏移量并相应地更新代码。