2013-10-11 5 views
1

J'ai créé une macro, mais elle a inséré le nom de fichier du fichier dans lequel j'étais lorsque je l'ai créée. Je veux l'utiliser pour de nombreux fichiers avec de nombreux noms différents (potentiellement des milliers de fichiers). Comment puis-je rendre la macro indépendante du nom de fichier? sous le nom de fichier "ADP" est utilisé et maintenant cette macro ne fonctionnera pas avec d'autres noms de fichiers, par ex. "CPL" ou "DKH"Excel Maco: comment utiliser un nom de fichier de variable

Columns("A:A").Select 
    Selection.Delete Shift:=xlToLeft 
    Range("A1").Select 
    Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select 
    ActiveWorkbook.Worksheets("ADP").Sort.SortFields.Clear 
    ActiveWorkbook.Worksheets("ADP").Sort.SortFields.Add Key:=Range("A1"), _ 
     SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 
    With ActiveWorkbook.Worksheets("ADP").Sort 
     .SetRange Range("A1:G7694") 
     .Header = xlNo 
     .MatchCase = False 
     .Orientation = xlTopToBottom 
     .SortMethod = xlPinYin 
     .Apply 
    End With 
    ActiveWorkbook.SaveAs Filename:="C:\Data\ADP.csv", _ 
     FileFormat:=xlCSV, CreateBackup:=False 
    ActiveWorkbook.Close 

Répondre

0

Enveloppez votre macro dans une procédure Sub avec des paramètres et de faire un deuxième sous ce qu'il appelle, comme si

Sub MyMacro(file as string, worksheetname as string) 
    Columns("A:A").Select 
    Selection.Delete Shift:=xlToLeft 
    Range("A1").Select 
    Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select 
    ActiveWorkbook.Worksheets(worksheetname).Sort.SortFields.Clear 
    ActiveWorkbook.Worksheets(worksheetname).Sort.SortFields.Add Key:=Range("A1"), _ 
     SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 
    With ActiveWorkbook.Worksheets(worksheetname).Sort 
     .SetRange Range("A1:G7694") 
     .Header = xlNo 
     .MatchCase = False 
     .Orientation = xlTopToBottom 
     .SortMethod = xlPinYin 
     .Apply 
    End With 
    ActiveWorkbook.SaveAs Filename:=file, _ 
     FileFormat:=xlCSV, CreateBackup:=False 
    ActiveWorkbook.Close 
End Sub 

Sub Usage() 
    MyMacro "C:\Data\ADP.csv", "ADP" 
    MyMacro "C:\Data\CPL.csv", "CPL" 
End Sub 
Questions connexes