.End(xlUp).row走得太远

时间:2018-07-13 09:27:08

标签: excel vba excel-vba

多亏了您,我找到了一个命令,因此它在我的表上运行时不幸地在我的表上运行了另一个命令,每次它都会移到第200行以上,而在这种情况下,我的表停在了第34行

Sub test0()
Dim ws As Worksheet
Set ws = Sheets("Detail")

Dim lr As Long
lr = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row
Range("F:I").NumberFormat = "General"
Dim arr
arr = Array("MFR", "CUSTLINE#", "PRICE (DYP)", "DELIVERY")
ws.Range("F1:I1").Value = arr
Dim ty
ty = Array("=IF(H2=""NB"","""",AY2)", "=A2", "=IF(P2="""",""NB"",P2)", "=IF(BR2>(D2+AM2),""STOCK"",IF(AR2=""0 Weeks"","""",SUBSTITUTE(AR2,"" Weeks"","" WKS"")))")
ws.Range("F2:I2" & lr).Formula = ty
End Sub

这是我用来使其正常工作的代码,我还尝试了此代码,只是为了查看我是否不知道数据不可见或什么:

Sub LastRowWithData_xlUp_1()

Dim lastRow As Long
lr = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row

MsgBox lr
End Sub

但是它给了我正确的行号。

与我尝试此操作相同:

Sub test1()
Dim ws As Worksheet
Set ws = Sheets("Detail")

Dim lr As Long
lr = InputBox("Last Row")
Range("F:I").NumberFormat = "General"
Dim arr
arr = Array("MFR", "CUSTLINE#", "PRICE (DYP)", "DELIVERY")
ws.Range("F1:I1").Value = arr
Dim ty
ty = Array("=IF(H2=""NB"","""",AY2)", "=A2", "=IF(P2="""",""NB"",P2)", "=IF(BR2>(D2+AM2),""STOCK"",IF(AR2=""0 Weeks"","""",SUBSTITUTE(AR2,"" Weeks"","" WKS"")))")
ws.Range("F2:I2" & lr).Formula = ty
End Sub

如果有人有一个想法,我将不胜感激,我真的不知道我在那儿错过了什么。

2 个答案:

答案 0 :(得分:1)

似乎您需要从公式中提到的作为原则的任何列中获得最大填充的行数。

另外,如果lr为99,则"F2:I2" & lr变为F2:I299

单次使用vars除非权宜之计,否则它们很少能提高代码的可读性或效率。 arr没有做任何这些事情,但我想说ty是有道理的。

Sub test1()

    Dim lr As Long, ty  AS VARIANT

    with workSheets("Detail")

        lr = application.max(.cells(.rows.count, "H").end(xlup).row, _
                             .cells(.rows.count, "P").end(xlup).row, _
                             .cells(.rows.count, "AR").end(xlup).row, _
                             .cells(.rows.count, "BR").end(xlup).row)

        .Range("F:I").NumberFormat = "General"

        .Range("F1:I1").Value = Array("MFR", "CUSTLINE#", "PRICE (DYP)", "DELIVERY")

        ty = Array("=IF(H2=""NB"", text(,), AY2)", "=A2", "=IF(P2= text(,), ""NB"", P2)", _
                   "=IF(BR2>(D2+AM2), ""STOCK"", " & _
                   "IF(AR2=""0 Weeks"", text(,), SUBSTITUTE(AR2, "" Weeks"", "" WKS"")))")

         .Range("F2:I" & lr).Formula = ty

    end with

End Sub

答案 1 :(得分:1)

问题在于ty的范围是F2:I2,而应该是F2:I

Sub test0()
Dim ws As Worksheet
Set ws = Sheets("Detail")

Dim lr As Long
lr = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row
Range("F:I").NumberFormat = "General"
Dim arr
arr = Array("MFR", "CUSTLINE#", "PRICE (DYP)", "DELIVERY")
ws.Range("F1:I1").Value = arr
Dim ty
ty = Array("=IF(H2=""NB"","""",AY2)", "=A2", "=IF(P2="""",""NB"",P2)", "=IF(BR2>(D2+AM2),""STOCK"",IF(AR2=""0 Weeks"","""",SUBSTITUTE(AR2,"" Weeks"","" WKS"")))")
ws.Range("F2:I2" & lr).Formula = ty
End Sub