脚本在另一个Sub中调用时不解析单元格,excel Vba

时间:2018-05-28 15:30:07

标签: excel vba excel-vba

我有一个脚本,它通过名为data的工作表中的列运行,并解析单元格长度以减少长度。放置在模块中并在工作表上运行时,此脚本可以正常工作。但是我遇到的问题是当我在整个脚本中调用它时。有没有人知道为什么它会运行但不起作用?

这是Sub

Sub Remove10()
Dim i As Long
Dim lr As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Data")

lr = ws.Cells(ws.Rows.Count, "T").End(xlUp).Row

For i = 2 To lr
    If Len(ThisWorkbook.Sheets("Data").Cells(i, 11).Value) > 8 Then Cells(i, 11).Value = Right(Cells(i, 11), 8)

Next i
End Sub

这就是所谓的

Private Sub RunFullAutomation_Click()
'----------------------------------------------------------------------------------------------
'This is the action that is taken when the "GO!" Button is pressed.
'Runs the following three subs in order without further need for user input.
'----------------------------------------------------------------------------------------------
'Get the data and set up the sheets
Call GetAndSetUpData
Call Remove10
Call RemoveYearsBefore18

Call RemoveYearsBefore16
'Data fixing
Call removeCancelledDescrepency
'report generation
Call FindExceptions
'Notify the user that the automation is all done
Range("CurrentTask").Value = "Complete"
End Sub

1 个答案:

答案 0 :(得分:1)

这可能是StackOveflow中最常见的VBA错误(来自经验):

Sub Remove10()
    Dim i As Long
    Dim lr As Long

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Data")
    lr = ws.Cells(ws.Rows.Count, "T").End(xlUp).Row

    For i = 2 To lr
        If Len(ws.Cells(i, 11)) > 8 Then ws.Cells(i, 11).Value = Right(ws.Cells(i, 11), 8)
    Next i
End Sub

问题在于,如果您未引用Worksheet的明确Cell,则会使用ActiveSheet。因此,如果Range()被破坏,试图从不同的细胞中获取细胞。