创建一个“导出”按钮,将查询表复制到desktp中的新工作簿并删除数据连接

时间:2016-09-12 14:43:38

标签: mysql excel excel-vba vba

您好,我在工作簿中有工作表,每个工作表都有自己的MySQL查询表。这些工作表上还有一些用户表单按钮,如刷新,转到第一行等。它们也有很少的计算列。

我想创建一个导出按钮,在没有数据连接和表单按钮的情况下复制(仅粘贴值)整个工作簿。

1 个答案:

答案 0 :(得分:1)

下面的代码将贯穿工作簿中的所有现有工作表,它将复制整个工作表单元格(值仅,没有表单控件或链接),并将它们粘贴到相同的结构中另一个保存在桌面上的工作簿。

Sub ExportCleanDataSheets()

Dim Sht             As Worksheet
Dim DestSht         As Worksheet
Dim DesktopPath     As String
Dim NewWbName       As String
Dim Wb              As Workbook
Dim i               As Long

Set Wb = Workbooks.Add

' set path to Dektop
DesktopPath = "C:\Users\" & Environ("USERNAME") & "\Desktop\"

' modify the name (I used "Clean_SQL_Data" and current date and time) to your needs
' i like to use the full date and time format, this way I don;t overwrite old files
NewWbName = "Clean_SQL_Data " & Format(Now, "yyyy_mm_dd _hh_mm_ss")
i = 1

' scroll through all sheets and copy the values only to the new workbook
For Each Sht In ThisWorkbook.Sheets

    If i <= Wb.Sheets.Count Then
        Set DestSht = Wb.Sheets(i)
    Else
        Set DestSht = Wb.Sheets.Add
    End If

    Sht.Cells.Copy
    With DestSht
        .Cells.PasteSpecial (xlPasteValues)
        .Cells.PasteSpecial (xlPasteFormats)
        .Name = Sht.Name
    End With

    i = i + 1
Next Sht

Application.DisplayAlerts = False

Wb.SaveAs Filename:=DesktopPath & NewWbName, FileFormat:=xlNormal
Wb.Close

Application.DisplayAlerts = True

End Sub