VBA For Loop仅适用于特定工作表

时间:2018-03-07 16:04:58

标签: excel vba excel-vba for-loop

我有以下代码,可以从电子表格中提取特定数据并将其格式化为表格。 for loops 都可以正常工作,但是第一个只有在我Sheet1上才有效,而第二个只有在我Sheet2上才有效

我无法解决如何重写它以使两段代码在电子表格中的任何位置都能正常工作。如果必须的话,最好来自Sheet1

Sub MakeMyTable()

Dim Col As Variant
Dim Col2 As Variant
Dim LastRow As Long
Dim R As Long
Dim StartRow As Long

Col = "D"
Col2 = "A"
StartRow = 1
X = 3    

'This with pulls the formatted data into totals into Sheet2

With Sheets("Sheet1")
    LastRow2 = Cells(Rows.Count, Col).End(xlUp).Row
    For R = StartRow + 1 To LastRow2 + 1 Step 1
        If .Cells(R, Col) = "" Then
        Sheets("Sheet2").Cells(1, "A").Value = "Project Cost Centers Costs At " & Date
        Sheets("Sheet2").Cells(X, "A").Value = .Cells(R - 1, Col).Value
        Sheets("Sheet2").Cells(X, "B").Value = .Cells(R - 1, "F").Value
        Sheets("Sheet2").Cells(X, "C").Value = .Cells(R, "P").Value
        Sheets("Sheet2").Cells(X, "C").NumberFormat = "$#,##0.00"
        X = X + 1
        End If
    Next R
End With

' This with finds any cell that has "RX04F.029.038" in it and moves it to the 
' bottom of the table.

With Sheets("Sheet2")
    LastRow2 = Cells(Rows.Count, Col2).End(xlUp).Row
    For R = LastRow2 To StartRow + 2 Step -1
            If InStr(1, Cells(R, Col2).Value, "RX04F.029.038") > 0 Then
            Rows(R).Cut
            Rows(LastRow2 + 1).Insert Shift:=xlDown
            R = R + 1
            LastRow2 = LastRow2 - 1             
        End If
    Next R
End With




End Sub

2 个答案:

答案 0 :(得分:0)

您可以将工作表名称更改为您想要的名称。

或者你可以交换:

With Sheets("Sheet1")

代表

With ActiveSheet

如果要在活动工作表上运行循环。

答案 1 :(得分:0)

您还需要将With语句正确链接到您使用的范围。例如,您使用Sheets("Sheet2"),但他们没有将lastRow2 = Cells().Row与其关联。对所有这样的实例执行此操作:LastRow2 = .Cells(.Rows.Count,Col2).End(xlUp).Row.否则,无论可能是什么,ActiveSheet上都会出现任何范围的使用。 - BruceWayne 3分钟前

编辑:BruceWayne在评论中给了我需要的答案,但不能将其标记为答案,所以这是我能做的最好的。谢谢