Excel VBA: how to add data validation list which contain comma included value without using reference of Range

我的未来我决定 提交于 2021-02-07 14:16:49

问题


I need to add a data validation list to Cell whose few values contains comma. I have the same problem like this Data Validation to Include Comma Character

But I can't reference a range, because I am creating a new workbook and feed its cell with the data validation list. So reference is not working for me and since some values contain comma so I can't set the Range into String and use that after Formula1

.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=myStr

Another idea I found that I can replace comma with other character(dummy character) and after populating the cell replace that dummy character with comma but problem is that how to replace that dummy character with comma ?

Another way is that override the Formula1 so that I can use dummy character as delimiter but I don't know how to achieve this.

Please suggest any solution, my final goal is to create a new workbook and populate it with data validation list through Excel VBA


回答1:


Let's use the dummy character method for cell B9. This sets up the DV:

Sub InternalString2()
    Range("B9").Select
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=Replace("alpha%ralpha,beta%waiter,gamma%hammer,delta%faucet","%",Chr(130))
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = False
    End With
End Sub

where Chr(130) is the dummy. The .ShowError is important.

Now to replace the dummy, we use the Event Macro:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, Range("B9")) Is Nothing Then Exit Sub

    Application.EnableEvents = False
        Range("B9").Replace What:=Chr(130), Replacement:=","
    Application.EnableEvents = True
End Sub



回答2:


As the other answer states, the comma cannot be escaped. The only solution, as far as I can see, is to add an extra worksheet to your new workbook, add the values there for your list, name that range, hide that sheet, and reference the named range. It's a fair few steps but really the only way.




回答3:


As the @snoopen suggest, I have create a Dummy Workbook which contains the data validation list and every time code runs it save as the Dummy Workbook to desired new file name. After that it populates that sheet with required data.



来源:https://stackoverflow.com/questions/35682142/excel-vba-how-to-add-data-validation-list-which-contain-comma-included-value-wi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!