简体   繁体   English

Excel VBA 2010:用VBA保存工作簿时,数据验证中断,但手动保存时,数据验证不中断

[英]Excel VBA 2010: Data validation breaks when workbook saved by VBA, but not when saved manually

CONTEXT AND WHAT WORKBOOK DOES I have a workbook for creating questionnaires; 上下文和工作簿我有一个用于创建调查表的工作簿。 the user selects from lists of questions across multiple tabs and then runs a macro which collates the selected questions into a new workbook; 用户从多个选项卡的问题列表中进行选择,然后运行一个宏,将选定的问题整理到新的工作簿中; the user would send the new 'published' workbook to their customer. 用户会将新的“已发布”工作簿发送给他们的客户。 Response type can also be selected with questions; 也可以选择带有问题的回复类型; eg "Yes/No", "1 to 5 score" etc. When the questions and tabs are collated the response type is added on the new workbook as data-validation; 例如,“是/否”,“ 1-5分”等。整理问题和选项卡后,响应类型将作为数据验证添加到新工作簿上。 the tab with the drop-down lists exists in the new workbook and is hidden. 具有下拉列表的选项卡在新工作簿中存在并且被隐藏。

BEHAVIOUR I'M SEEING Everything works while the workbook is still open following creation; 行为,我正在查看当工作簿在创建后仍处于打开状态时,一切正常。 however when I close and re-open I get the standard error "Unreadable content found... Do you want to repair... " The repair by excel removes all the data validation from all tabs! 但是,当我关闭并重新打开时,出现标准错误“找到了无法读取的内容...您要修复...” excel进行的修复从所有选项卡中删除了所有数据验证! This only happens when the file is created and saved through VBA ; 当通过VBA创建并保存文件时才会发生这种情况; creating and saving files manually I do not get this error. 手动创建和保存文件我没有收到此错误。 I have also, for example, tried using the same VBA code for adding the data validation, on a new workbook created by myself, and this issue doesn't happen. 例如,我还尝试在我自己创建的新工作簿上使用相同的VBA代码添加数据验证,并且不会发生此问题。

Notes on code; 代码注释; workflow, and what I've tried follow: 工作流程,以及我尝试过的工作:

Code to create and save new workbook 创建和保存新工作簿的代码

outFileName = Application.GetSaveAsFilename(InitialFileName:=standardName, FileFilter:="Excel Files (*.xlsm), *.xlsm", Title:="Save As")

If outFileName = "FALSE" Then
    MsgBox ("Export NOT completed")
    GoTo endSafely
Else
outFileName = outFileName
End If

Set outBook = Workbooks.Add

'Activate and save the workbook
outBook.Activate
outBook.SaveAs Filename:=outFileName, FileFormat:=52

Code to apply data validation 应用数据验证的代码

    Sub addResponseFormatting(targetBook, targetSheet, targetRow, targetColumn, typeResponse)


Set targetBook = Workbooks(targetBook)
Set thisBook = Workbooks(ThisWorkbook.Name)

'---------------------------------------------------------------------------------------------------
'  PROCESS
'---------------------------------------------------------------------------------------------------

targetBook.Activate
targetBook.Sheets(targetSheet).Activate

Dim targetCell As Range

With targetBook.Sheets(targetSheet).Cells(targetRow, targetColumn).Validation


    Select Case typeResponse

        Case "Yes/No"

                .Delete
                .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
                xlBetween, Formula1:="=DropDowns!$D$4:$D$5"
                .IgnoreBlank = True
                .InCellDropdown = True
                .InputTitle = ""
                .ErrorTitle = ""
                .InputMessage = ""
                .ErrorMessage = ""
                .ShowInput = True
                .ShowError = True


        Case "1 to 5"

                .Delete
                .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
                xlBetween, Formula1:="=DropDowns!$C$4:$C$8"
                .IgnoreBlank = True
                .InCellDropdown = True
                .InputTitle = ""
                .ErrorTitle = ""
                .InputMessage = ""
                .ErrorMessage = ""
                .ShowInput = True
                .ShowError = True

        Case Else
            'Do nothing; leave open as free text
            'Removes all validation; note this may also remove tooltip messages if we've applied these
            .Delete
    End Select

End With


End Sub

Workflow 工作流程

  1. Create and save new workbook - "Workbook-B" 创建并保存新工作簿-“ Workbook-B”
  2. Copy the 'DropDowns' tab across 复制“ DropDowns”标签
  3. For each tab in Master Workbook, "Workbook A", if tab flagged as 'Use', copy tab to Workbook-B (no data validation yet; just a list beside each question of what response type is wanted) 对于“主工作簿”中“工作簿A”中的每个选项卡,如果该选项卡标记为“使用”,则将其复制到工作簿B(尚无数据验证;仅是每个问题需要哪种响应类型的列表)
  4. For each tab in Workbook-B, cut down content on sheet to what customer needs to see (eg removing un-used questions), and apply data validation corresponding to the response type selected 对于Workbook-B中的每个选项卡,将工作表上的内容缩减到客户需要查看的内容(例如,删除未使用的问题),并应用与所选响应类型相对应的数据验证
  5. Save the workbook again 再次保存工作簿

Things I've tried 我尝试过的事情

  • The cells which the validation goes on are merged; 进行验证的单元将合并; I've experimented with a fresh workbook using the same validation code to add validation to merged cells, hiding/showing the Dropdown sheet, applying validation manually vs. with code, and the issue always recurs only if VBA created and saved the workbook 我已经尝试过使用相同的验证代码向合并的单元格添加验证,隐藏/显示“下拉列表”,手动验证以及使用代码的新工作簿,并且只有在VBA创建并保存了工作簿的情况下,问题才会再次出现
  • Saving file as macro/non-macro workbook makes no difference: (xlsx, xlsm) 将文件另存为宏/非宏工作簿没有任何区别:(xlsx,xlsm)
  • Tried copying the code into a new module in case corrupted 尝试将代码复制到新模块中以防损坏
  • Experimented with specifying/not specifying Excel file type on the .SaveAs command; 尝试在.SaveAs命令中指定/不指定Excel文件类型; tried different file type filters 尝试了不同的文件类型过滤器

Everything else on file is as expected 文件上的其他所有内容均符合预期

Other notes 其他注意事项

  • Using Excel 2010; 使用Excel 2010; file is saved as xlsx; 文件另存为xlsx; file is opened on Excel 2010 again 再次在Excel 2010上打开文件
  • I found another similar thread however the issue there was related to the Drop-down boxes remaining linked to the source workbook; 我发现了另一个类似的线程,但是那里的问题与下拉框保持链接到源工作簿有关。 this wouldn't happen in my case (I pre-empted in my code) because there is no datavalidation until the workbook exists and already has all the copied tabs into it; 在我的情况下,这不会发生(我在代码中先占),因为在工作簿存在并且所有复制的选项卡都放入其中之前,没有数据验证; the macro adds the data validation and points it at the DropDowns tab existing in the workbook. 宏将添加数据验证并将其指向工作簿中现有的“ DropDowns”选项卡。

Has anyone else had and fixed this issue? 还有其他人解决此问题吗?

This is my first post here so I hope I've been thorough. 这是我在这里的第一篇文章,所以我希望我做的透彻。 Thankyou. 谢谢。

I found the root of the issue: some other data validation was being copied across with my tabs and their Source (list-type validation) was still linked to the original workbook - this caused an error and when Excel tried to repair the file it would remove all the data validation from a tab (not just that with the error). 我找到了问题的根源:一些其他数据验证与我的选项卡一起复制,并且它们的源(列表类型验证)仍链接到原始工作簿-这导致错误,并且当Excel尝试修复文件时,它将从标签中删除所有数据验证(不仅仅是带有错误的数据验证)。

To identify which cells gained and lost data validation I used this simple bit of code to highlight cells with validation: 为了确定哪些单元格获得和丢失了数据验证,我使用了以下简单的代码来突出显示带有验证的单元格:

Sub routine (data valdation check function follows) 子例程 (后面是数据验证检查功能)

Sub runascan()

Set targetBook = Workbooks("test25")

targetBook.Activate

For Each sheetsIn In targetBook.Sheets

    sheetsIn.Activate

    For Each cellin In Range("A1:Z100")

        If checkVal(cellin) = 1 Then
            cellin.Interior.Color = RGB(0, 255, 0)
        Else

        End If
   Next cellin

Next sheetsIn

End Sub

Function to check if data validation in a cell 检查单元格中的数据验证功能

Function checkVal(tRange)

Workbooks(ThisWorkbook.Name).Activate

x = 0
On Error Resume Next
x = tRange.SpecialCells(xlCellTypeSameValidation).Count

On Error GoTo 0

If x = 0 Then
    checkVal = 0
Else
    checkVal = 1
End If

End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM