验证列表自动将字符串转换为VBA中的日期

Ben*_*rIO 5 excel vba

我正在尝试使用工作表的名称创建验证列表.第一部分我在一个数组上添加每个工作表的名称(表格类似于"2018年1月","2018年2月"等),第二部分通过使用逗号分隔符连接数组的每个部分来创建List.

问题是ValidationList将我的字符串转换为"2018年1月"到日期格式"Jan-18".我不能继续我的代码,因为不尊重表名...

这是我的代码:

Sub RefreshMonth()
Dim xsheet as Worksheets
Dim monthList(20) As String
Dim valList As String


''' This part add every sheet names on an array and work well '''
i = 0
For Each xsheet In ActiveWorkbook.Sheets()
    If xsheet.Name Like "*20*" Then
        monthList(i) = xsheet.Name
        i = i + 1
    End If
Next xsheet


'This part create the validation list, where the unwanted conversion happend '''
With Range("B1").Validation
    .Delete
    .Add Type:=xlValidateList, _
          Formula1:=Join(monthList, ",")
End With
Run Code Online (Sandbox Code Playgroud)

在这里,我的ValidationList在代码运行后使用不需要的转换的sheetname作为日期格式: 在此输入图像描述

我尝试使用CStr()甚至在join()之后重新执行字符串转换,但是现在我没有找到任何工作.

非常感谢提前寻求帮助

小智 3

尝试一下,这是稍微不同的方法,您首先将所有工作表名称保存在工作表中的某个位置(我使用了 AA 列,但您可以更改它),然后分配此范围进行验证。

Sub RefreshMonth()
Dim xsheet As Worksheet
Dim valList As String
Dim validationrange As Range

i = 1
For Each xsheet In ThisWorkbook.Worksheets
    If xsheet.Name Like "*20*" Then
        Range("AA" & i).NumberFormat = "@"
        Range("AA" & i) = xsheet.Name
        i = i + 1
    End If
Next xsheet

Set validationrange = Range("AA1:AA" & i - 1)
With Range("B1").Validation
    .Delete
    .Add Type:=xlValidateList, Formula1:="=" & validationrange.Address
End With
End Sub
Run Code Online (Sandbox Code Playgroud)