Form Combobox上的Excel VBA循环单元链接

时间:2015-10-24 10:44:54

标签: excel excel-vba vba

我需要一个可以使用循环更改活动工作表上已存在的表单控件组合框上的单元格链接的函数。我现在可以通过如下循环来实现这个目的

ActiveSheet.Shapes("Combobox 1").OLEFormat.Object.LinkedCell = Worksheets("Test").Cells(2, 2).Address
ActiveSheet.Shapes("Combobox 2").OLEFormat.Object.LinkedCell = Worksheets("Test").Cells(2, 3).Address
ActiveSheet.Shapes("Combobox 3").OLEFormat.Object.LinkedCell = Worksheets("Test").Cells(2, 4).Address
ActiveSheet.Shapes("Combobox 4").OLEFormat.Object.LinkedCell = Worksheets("Test").Cells(2, 5).Address
ActiveSheet.Shapes("Combobox 5").OLEFormat.Object.LinkedCell = Worksheets("Test").Cells(2, 6).Address
ActiveSheet.Shapes("Combobox 6").OLEFormat.Object.LinkedCell = Worksheets("Test").Cells(2, 7).Address
ActiveSheet.Shapes("Combobox 7").OLEFormat.Object.LinkedCell = Worksheets("Test").Cells(2, 8).Address

所以我想使用循环而不是必须为我的工作表上的每个组合框执行此操作,循环需要增加.Cell行号和.Shape(“Combobox 1”)。我一直在编写循环,因为组合框使用的是名称或字符串值,而不是int值。

对此的任何帮助都将非常感激

1 个答案:

答案 0 :(得分:1)

使用以下格式:

Dim ws1 As Worksheet, ws2 As Worksheet, i As Long, os As Long

Set ws1 = ActiveSheet
Set ws2 = Worksheets("Test")

os = 1     'change i Offset as needed

For i = 1 To 7
    ws1.Shapes("Combobox " & i).OLEFormat.Object.LinkedCell = ws2.Cells(2, i + os).Address
Next