使用下拉列表更改列中的所有单元格

问题描述 投票:-1回答:1

我正在尝试使用下拉列表替换列中的所有单元格以使用excel宏。我也在尝试使用动态范围,因为我不知道列表有多长。这是我现在的代码:

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("*Name of main sheet*")
Set StartCell = Range("A1")

'Find Last Row and Column
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

'Select Range

Worksheets("*Name of main sheet*").Activate

'replace "J2" with the cell you want to insert the drop down list
With Range(StartCell, sht.Cells(LastRow, LastColumn))
    .Delete
    'replace "=A1:A6" with the range the data is in.
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
         Operator:=xlBetween, Formula1:="=Sheet1!A1:A6"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

我在一个名为Sheet1的单独选项卡中创建了包含所有下拉选项的列表。

excel vba excel-vba
1个回答
0
投票

.Validation的末尾添加With Range(StartCell, sht.Cells(LastRow, LastColumn))并使用$来保持行参考固定

所以整个With-End块成为:

With Range(StartCell, sht.Cells(LastRow, LastColumn)).Validation
    .Delete
    'replace "=A1:A6" with the range the data is in.
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
         Operator:=xlBetween, Formula1:="=Sheet1!A$1:A$6"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

如果你需要保持下拉列表动态与Sheet1列A不是空值,那么你可以如下:

Dim LastRow As Long
Dim LastColumn As Long

Dim sourceSht As Worksheet
Set sourceSht = Worksheets("Sheet1")

With Worksheets("Name of main sheet")
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).row
    LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
    With .Range("A1", .Cells(LastRow, LastColumn)).Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
             Operator:=xlBetween, Formula1:="=" & sourceSht.name & "!" & sourceSht.Range("A1", sourceSht.Cells(sourceSht.Rows.Count, 1).End(xlUp)).Address(True, False)
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
End With
© www.soinside.com 2019 - 2024. All rights reserved.