简体   繁体   中英

Excel VBA - Making a macro valid for all worksheets in workbook

I have a workbook with several sheets, (file1, file2, file3, etc), and I'm working on a macro that will parse an external file and paste the contents in the active worksheet. The issue is that I would like to make my PasteStart below not specific so it will work on any active worksheet , not only file1, without specifying its name. I tried using sthg like Variable = ACtiveSheet.Name but I get runtime error 242.

Sub Import1()

Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Sheet As Worksheet
Dim PasteStart As Range


Application.ScreenUpdating = False
Set wb1 = ActiveWorkbook
Set PasteStart = [file1.C5]

FileToOpen = Application.GetOpenFilename _
(Title:="Please choose an XLIFF to Parse", _
FileFilter:="Report Files *.xlf (*.xlf),")

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

    For Each Sheet In wb2.Sheets
        With Sheet.UsedRange
            .Copy PasteStart
            Set PasteStart = PasteStart.Offset(.Rows.Count)
        End With
    Next Sheet

End If
wb2.Close
Range("C5:L3146").Select
    Selection.Delete Shift:=xlToLeft
    Range("D6:D2337").Select
    Selection.Delete Shift:=xlToLeft
    Range("E6:G2307").Select
    Selection.Delete Shift:=xlToLeft
End Sub
Set PasteStart = Activesheet.Range("A1") 

should work.

Also:

Range("C5:L3146").Select
    Selection.Delete Shift:=xlToLeft
    Range("D6:D2337").Select
    Selection.Delete Shift:=xlToLeft
    Range("E6:G2307").Select
    Selection.Delete Shift:=xlToLeft

should probably be something like:

With PasteStart.Parent
    .Range("C5:L3146").Delete Shift:=xlToLeft
    .Range("D6:D2337").Delete Shift:=xlToLeft
    .Range("E6:G2307").Delete Shift:=xlToLeft
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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