Excel宏:如何使用变量文件名

时间:2013-10-11 18:12:53

标签: excel excel-vba filenames vba

我创建了一个宏,但它已经从我创建的文件中插入了文件名。我想将它用于许多不同名称的文件(可能有数千个文件)。如何使宏独立于文件名?在文件名下面使用“ADP”,现在这个宏不能用于其他文件名,例如“CPL”或“DKH”

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

1 个答案:

答案 0 :(得分:0)

将宏包含在带有参数的Sub过程中,然后创建第二个调用它的子句,如下所示

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