我正在尝试为" n"中的多个下拉列表编写宏。列中的单元格(让我们说100)。这些下拉列表的范围(下拉值)必须从具有相同行数的表中选取(在我们的示例中为100)。
我无法为公式部分运行for循环(下面突出显示)。我希望宏选择D2:H2范围为i = 2,D3:H3为i = 3,依此类推。我该怎么做?有没有替代方案?
期待有价值的投入。 谢谢!
Sub S_Dropdown3()
Dim wks As Worksheet: Set wks = Sheets("Sheet1")
wks.Select
Dim i As Integer
For i = 2 To 101
With Range("B" & i).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, **Formula1:="=Sheet2!D2:H2"**
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Next i
End Sub
答案 0 :(得分:1)
以下代码应该有效:
Option Explicit
Sub S_Dropdown3()
Dim wks As Worksheet
Dim i As Integer
Set wks = ThisWorkbook.Worksheets("Sheet1")
wks.Activate
For i = 2 To 101
With wks.Range("B" & i).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=Sheet2!D" & i & ":H" & i
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Next i
End Sub
实施了更改:
Sheet1
在运行宏的工作簿中引用Sheet1
(如果打开了多个Excel文件)。.Selected
仅选择范围。表格只能是.Activated
。早期版本的Excel并不介意。从来没有版本的Excel会在该行中引发错误。.Range("B" & i)
。