使用 VBA 将下拉列表添加到动态创建的工作簿
Add drop down list to dynamically created workbook with VBA
我正在使用宏在我的工作簿中创建一个临时 sheet,用数据填充 sheet 上的一堆单元格,将 sheet 导出到新工作簿,然后关闭新工作簿。
一切正常。我想要做的是向临时 sheet(以及因此的新工作簿)添加一个下拉列表,其中包含添加到所述 sheet 的单元格值列表。所以我用谷歌搜索了如何做到这一点并发现了这段代码:
Sub main()
'replace "J2" with the cell you want to insert the drop down list
With Range("J2").Validation
.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
End Sub
我将其合并到我的项目中,进行了必要的参考更改并进行了试用,但是当我打开新工作簿时,下拉菜单不存在。关于如何让它工作有什么建议吗?
Range("J2").Validation
在您 运行 代码时引用活动 sheet - 您应该使用显式引用,例如wsTemp.Range("J2") 其中 wsTemp 是您之前添加的 sheet。
此外:您还必须将 Sheet1 复制到新工作簿 - 因为您从那里获取验证列表值。在复制临时 sheet 之前复制此 sheet - 为了安全起见。
我正在使用宏在我的工作簿中创建一个临时 sheet,用数据填充 sheet 上的一堆单元格,将 sheet 导出到新工作簿,然后关闭新工作簿。
一切正常。我想要做的是向临时 sheet(以及因此的新工作簿)添加一个下拉列表,其中包含添加到所述 sheet 的单元格值列表。所以我用谷歌搜索了如何做到这一点并发现了这段代码:
Sub main()
'replace "J2" with the cell you want to insert the drop down list
With Range("J2").Validation
.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
End Sub
我将其合并到我的项目中,进行了必要的参考更改并进行了试用,但是当我打开新工作簿时,下拉菜单不存在。关于如何让它工作有什么建议吗?
Range("J2").Validation
在您 运行 代码时引用活动 sheet - 您应该使用显式引用,例如wsTemp.Range("J2") 其中 wsTemp 是您之前添加的 sheet。
此外:您还必须将 Sheet1 复制到新工作簿 - 因为您从那里获取验证列表值。在复制临时 sheet 之前复制此 sheet - 为了安全起见。