我在工作簿的“Sheet2”中制作了发票格式。我附上了一个查询。我使用单元格“E9”中的数据验证列表更改值。
我按下按钮来调用刷新工作簿中的查询,以便我的发票发生变化:
Sub RefreshAll()
' Replace "YourWorkbookName.xlsx" with the actual name of your workbook
Workbooks("TEA.xlsm").RefreshAll
End Sub
我希望数据验证中的每个值都刷新查询,等待其完全完成,然后将工作表导出为具有相同名称的单独 Excel 工作表。
Public Sub Create_workbooks()
Dim destinationFolder As String
Dim dataValidationCell As Range, dataValidationListSource As Range, dvValueCell As Range
destinationFolder = "C:\Users\Maqlly\Desktop\Vouchers" 'Same folder as workbook containing this macro
'destinationFolder = "C:\path\to\folder\" 'Or specific folder
If Right(destinationFolder, 1) <> "\" Then destinationFolder = destinationFolder & "\"
'Cell containing data validation in-cell dropdown
Set dataValidationCell = Worksheets("sheet2").Range("E9")
'Source of data validation list
Set dataValidationListSource = Evaluate(dataValidationCell.Validation.Formula1)
'Create Separate Workbooks for each data validation value
For Each dvValueCell In dataValidationListSource
Call RefreshAll
Application.Wait (Now + TimeValue("00:00:10"))
dataValidationCell.Value = dvValueCell.Value
Worksheets("sheet2").Copy
'there is now a new active workbook
With ActiveWorkbook
.SaveAs Filename:=destinationFolder & dvValueCell.Value, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
.Close False
End With
Next
End Sub
它正在单独导出工作表,但无法刷新查询以更改发票。
我虽然这是所需时间的问题,但似乎不是因为我添加了等待协议以便它完成。
将
QueryTable.BackgroundQuery
设置为 false 将解决该问题。
您可以手动选择每个表,转到“查询”选项卡 ->“属性”并取消选中“启用后台刷新”。
或者我们可以使用 VBA 来完成。
Sub SetAllQueryTablesBackgroundQueryToFalse()
Dim ws As Worksheet
Dim ListObject As ListObject
' Loop through each worksheet in the workbook
For Each ws In ThisWorkbook.Worksheets
' Loop through each query table in the worksheet
For Each ListObject In ws.ListObjects
If Not ListObject.QueryTable Is Nothing Then
ListObject.QueryTable.BackgroundQuery = False
End If
Next
Next ws
End Sub