迭代数据验证列表

时间:2018-05-07 14:58:51

标签: excel vba excel-vba

我创建了一个按钮就是这个宏:

Sub loopthroughvalidationlist()
     Dim inputRange As Range
     Dim c As Range
     Set inputRange = Evaluate(Range("A9").Validation.Formula1)
     path = "C:\test\"
     For Each c In inputRange
        filename1 = Range("B18").Text
        ActiveWorkbook.SaveCopyAs filename:=path & filename1 & ".xlsm"
    Next c
End Sub

验证列表包含大约5个名称。但由于某种原因,它只保存了1个文件。

1 个答案:

答案 0 :(得分:1)

  • 只要您在访问数据验证列表时没有遇到任何问题,我就会在Range("A1:A5")中对其进行硬编码。
  • 我已使用ActiveWorkbook更改ThisWorkbook以查看其工作原理。 - 生成有效ThisWorkbook.Save和有效.FullName
  • 需要.Path
  • 棘手的部分是保存excel文件的oldPathFulloldPath,并在每个循环中使用ThisWorkbook.SaveAs oldPathFull
  • Application.DisplayAlerts = False禁用Excel提示。如果您愿意,可以将它放在循环外。
Sub LoopThroughValidationList()

     Dim inputRange     As Range
     Dim c              As Range
     Dim oldPathFull    As String
     Dim oldPath        As String

     Set inputRange = Range("A1:A5")
     ThisWorkbook.Save
     oldPathFull = ThisWorkbook.FullName
     oldPath = ThisWorkbook.Path & "\"

     For Each c In inputRange
        Application.DisplayAlerts = False
        ThisWorkbook.SaveCopyAs Filename:=oldPath & c & ".xlsb"
        ThisWorkbook.SaveAs oldPathFull
        Application.DisplayAlerts = True
    Next c

End Sub

一旦您能够使用预定义值运行代码,这是一个[MCVE]示例,如何获取单元格B1的数据验证值:

Public Sub TestMe()

    Dim myCell              As Range
    Dim valRules            As Range

    Set valRules = Evaluate(Range("A1").Validation.Formula1)

    For Each myCell In valRules
        Range("A1") = myCell
        Debug.Print Range("A1")
    Next myCell

End Sub