根据vba

时间:2016-03-14 15:39:15

标签: excel vba excel-vba

我正在尝试根据列中的唯一值创建多个工作簿。我的代码根据列中的唯一值创建了第一个具有唯一值名称(Col C)的工作簿“c'但后来它没有用。

ColA        colB          Colc(uniques values)
1.John      ram           micheal
2.Andrea    Boll          Holger
3.schmidt   Muller        Arnold
4.ram       loki          rainer
5.puv      ramesh        shanu
6.jogesh   naga          chiru

代码:

 Dim i As Integer
 Dim x As String
 Dim LastRow as integer

LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row

 For i = 2 To LastRow     
     x = ActiveWorkbook.Sheets(3).Range("C" & i).Value

    Set NewBook = Workbooks.Add
    With NewBook
        .Title = x

        .SaveAs Filename:=x & ".xlsx"
    End With
    Next 

结果:

Micheal.xlsx
Holger.xlsx
Arnold.xlsx
rainer.xlsx
shanu.xlsx
chiru.xlsx

我只有micheal.xlsx工作簿。有人可以看看我的代码并纠正我。

1 个答案:

答案 0 :(得分:1)

有两个问题: 1.您没有在代码中声明LastRow。 2.您需要将ActiveWorkbook更改为ThisWorkbook。因为当您创建新工作簿时,新工作簿将成为活动工作簿,代码将不再起作用。使用ThisWorkbook时,不会发生此错误。

Public Sub CreateSomeWorkbooks()

Dim i As Integer
Dim x As String
Dim LastRow As Long

LastRow = ThisWorkbook.Sheets(3).Cells(ThisWorkbook.Sheets(3).Rows.Count, "C").End(xlUp).Row

For i = 2 To LastRow
    x = ThisWorkbook.Sheets(3).Range("C" & i).Value
    Set NewBook = Workbooks.Add
    With NewBook
        .Title = x
        .SaveAs Filename:=x & ".xlsx"
    End With
Next i

End Sub