我有另一个问题。我想知道如何从一列中检索数据并根据比较运算符将其放在另一列中。以下是我到目前为止的情况:
Sub addcolrows()
Dim PTotal As Range, Shipping As Range, ShipWeight As Range, MyTotal As Range, R As Range
Set PTotal = Range("AH2:AH16254")
Set PTotalAndShipping = Range("AI2:AI16254")
Set ShipWeight = Range("U2:U16254")
Set MyTotal = Range("AJ2:AJ16254")
PTotal.Value = "=SUM(E2 + 3,)"
For Each R In ShipWeight
If R <= 0.16 Then
PTotalAndShipping.Value = "=SUM(AH2 + 5, )"
ElseIf R > 0.16 & R < 10 Then
PTotalAndShipping.Value = "=SUM(AH2 + 10, )"
ElseIf R > 10 & R < 20 Then
PTotalAndShipping.Value = "=SUM(AH2 + 15, )"
ElseIf R > 20 & R < 30 Then
PTotalAndShipping.Value = "=SUM(AH2 + 20, )"
ElseIf R > 30 & R < 40 Then
PTotalAndShipping.Value = "=SUM(AH2 + 25, )"
ElseIf R > 40 & R <= 50 Then
PTotalAndShipping.Value = "=SUM(AH2 + 30, )"
Else: PTotalAndShipping.Value = "=SUM(, )& "" NA """
End If
Next
End Sub
我有不同的运输重量,根据重量等级,我希望在我的“PTotalAndShipping”栏中更改数据,即“AI”。它工作但列中的计算数字可能是错误的,它们会一直闪烁,我的Excel应用程序会冻结。
有什么建议吗?
答案 0 :(得分:0)
首先,每次循环时,您在整个列(AH)中输入相同的公式
您可以返回R.Row的值,然后将您想要的公式添加到PTotalAndShipping.cells(R.Row - 1,1)
i = R.Row
PTotalAndShipping.cells(i - 1, 1) = "=SUM(AH" & i & + 5, )"
其次,&符号(&amp;)是串联字符。您需要使用AND关键字
ElseIf R > 0.16 AND R < 10 Then
第三,如果体重是10(你有小于或大于,但不等于),你还没有捕捉到会发生什么。
最后,为了避免屏幕闪烁,请尝试关闭计算和屏幕更新,只需记住在代码末尾再次打开它们。您会发现最好在错误处理程序中处理此问题。
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
我认为这应该涵盖你要做的事情:
Dim PTotal As Range, Shipping As Range, ShipWeight As Range, MyTotal As Range, R As Range, PTotalAndShipping As Range
Dim i As Long
Set PTotal = Range("AH2:AH16254")
Set PTotalAndShipping = Range("AI2:AI16254")
Set ShipWeight = Range("U2:U16254")
Set MyTotal = Range("AJ2:AJ16254")
On Error GoTo exitHere
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
PTotal.Value = "=SUM(E2 + 3,)"
For Each R In ShipWeight
i = R.Row
If R.Cells.Value <= 0.16 Then
PTotalAndShipping.Cells(i - 1).Value = "=SUM(AH" & i & " + 5, )"
ElseIf R.Value > 0.16 And R <= 10 Then
PTotalAndShipping.Cells(i - 1).Value = "=SUM(AH" & i & " + 10, )"
ElseIf R.Value > 10 And R <= 20 Then
PTotalAndShipping.Cells(i - 1).Value = "=SUM(AH" & i & " + 15, )"
ElseIf R.Value > 20 And R <= 30 Then
PTotalAndShipping.Cells(i - 1).Value = "=SUM(AH" & i & " + 20, )"
ElseIf R.Value > 30 And R <= 40 Then
PTotalAndShipping.Cells(i - 1).Value = "=SUM(AH" & i & " + 25, )"
ElseIf R.Value > 40 And R <= 50 Then
PTotalAndShipping.Cells(i - 1).Value = "=SUM(AH" & i & " + 30, )"
Else: PTotalAndShipping.Cells(i - 1).Value = "=SUM(, )& "" NA """
End If
Next
exitHere:
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
这只是一个快速尝试让你当前的代码工作,希望它有所帮助。