2015-02-24 319 views
1

我是VBA的新手,無法獲得loop的工作。Excel VBA,循環

J列包含某些ID號。對於每個ID號我有幾行顯示在我的數據庫中。我將我的數據庫排序在J列(升序)。 我想篩選列J中的所有值,並將每個ID號的所有行復制到新表中,我想將其重命名爲ID號。 這裏是宏,但loop不起作用(Run-time error 13, Type mismatch, error in the following code row: For i = 45 To LastEmpNo

任何幫助將受到歡迎。謝謝

Sub Macro3() 

Dim MyDataFirstCell 
Dim MyDataLastCell 
Dim EmpNoStart 
Dim EmpNoFinish 
Dim i As Integer 

Range("A1").Select 
MyDataFirstCell = ActiveCell.Address 
Selection.End(xlDown).Select 
Selection.End(xlToRight).Select 
MyDataLastCell = ActiveCell.Address 

Range("J2").Select 
EmpNoStart = ActiveCell.Address 
Selection.End(xlDown).Select 
EmpNoFinish = ActiveCell.Address 

Range(EmpNoStart & ":" & EmpNoFinish).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Columns _ 
    ("K:K"), Unique:=True 

Dim FirstEmpNo 
Dim LastEmpNo 

Range("K2").Select 
FirstEmpNo = ActiveCell.Address 
Selection.End(xlDown).Select 
LastEmpNo = ActiveCell.Address 

For i = FirstEmpNo To LastEmpNo 

    Range("J1").Select 
    Selection.AutoFilter 
    ActiveSheet.Range(MyDataFirstCell & ":" & MyDataLastCell).AutoFilter Field:=10, Criteria1:=i 
    Rows("1:1").Select 
    Range("C1").Activate 
    Range(Selection, Selection.End(xlDown)).Select 
    Selection.Copy 
    Sheets.Add After:=Sheets(Sheets.Count) 
    ActiveSheet.Paste 
    Columns("B:B").EntireColumn.AutoFit 
    Cells.Select 
    Cells.EntireColumn.AutoFit 
    Sheets("Sheet1").Select 
    Sheets("Sheet1").Name = i 

Next i 


End Sub 

回答

1

您不能從一個字符串值迭代到另一個字符串值。 「For」循環需要兩個數字值。

?activecell.Address 
$C$9 
?activecell.Row 
9 

因此:

FirstEmpNo = ActiveCell.Row 
Selection.End(xlDown).Select 
LastEmpNo = ActiveCell.Row