复制其他工作簿中的数据,取消隐藏列,然后先关闭自动过滤器,粘贴到当前工作簿中,然后关闭工作簿

时间:2019-07-16 07:25:51

标签: excel vba

试图获取一个提示用户打开xlsm文件的宏,转到特定标签,取消隐藏列并关闭过滤器,选择所有数据,然后粘贴到名为 RRImport的新标签中

示例:在名为 MergedData.xlsm 的文件中,运行宏以打开 Jul01Data.xlsm ,在其中选择“已查看数据” 标签 Jul01Data.xlsm ,取消隐藏所有列并关闭“已查看数据” 标签中的所有过滤器,复制所有数据,在 MergedData.xlsm < / em>称为“ RRImport” ,并粘贴特殊值来存储“ RRImport” 的单元格A1中的所有数据。关闭 Jul01Data.xlsm 而不保存任何更改

Sub ImportSheet()


Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "RRImport"
Sheets("RRImport").Select

Application.DisplayAlerts = False

Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Sheet As Worksheet

Set wb1 = ActiveWorkbook


FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Append to Merged Data", _
FileFilter:="Report Files *.xlsm (*.xlsm),")

If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(Filename:=FileToOpen)
End If

wb2.Sheets("Reviewed Data").Select
' HERE IS WHERE I GET THE ERROR, IR WON'T UNHIDE THE FILTERS    
    If wb2.AutoFilterMode Then
    wb2.AutoFilterMode = False
    End If

Columns("A:M").Select
Selection.Copy
wb1.Sheets("RRImport").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

wb2.Close

End Sub

2 个答案:

答案 0 :(得分:0)

因此,在此过程中,我将添加说明。

首先,您选择了工作表,但是在引用整个工作簿(而不是工作表)时,代码继续执行。

这意味着,您无需选择工作表,只需引用它即可,就像您引用工作簿一样。

如果不是

wb2.Sheets("Reviewed Data").Select
' HERE IS WHERE I GET THE ERROR, IR WON'T UNHIDE THE FILTERS    
    If wb2.AutoFilterMode Then
    wb2.AutoFilterMode = False
    End If

您写了

    If wb2.Sheets("Reviewed Data").AutoFilterMode Then
    wb2.Sheets("Reviewed Data").AutoFilterMode = False
    End If

答案 1 :(得分:0)

它现在应该可以工作:

AutoFilterMode是工作表属性,而不是工作簿属性。

Sub ImportSheet()

Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Sheet As Worksheet

Set wb1 = ActiveWorkbook


FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Append to Merged Data", _
FileFilter:="Report Files *.xlsm (*.xlsm),")

If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set wb2 = Workbooks.Open(filename:=FileToOpen)
End If

    If wb2.Sheets("Reviewed Data").AutoFilterMode Then
        wb2.Sheets("Reviewed Data").AutoFilterMode = False
    End If

Dim ws As Worksheet

wb1.Activate
Set ws = wb1.Worksheets.Add(, ActiveSheet)
ws.Name = "RRImport"
wb2.Sheets("Reviewed Data").Columns("A:M").Copy

ws.Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

wb2.Close False


End Sub

我还做了一些其他更改。