简体   繁体   中英

Insert formulas (range) then copy>paste values only

I want to make a macro that copies formulas into the range Q6:Q2500 . After the macro inserted the formulas it should copy>paste values only.

[...]
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

Range("Q6").Formula = "=IF(INDIRECT(""A""&ROW())="""","""",CONCATENATE(INDIRECT(""A""&ROW()),""/"",INDIRECT(""B""&ROW()),""/"",INDIRECT(""E""&ROW()),""/"",INDIRECT(""P""&ROW())))"
Range("Q6").Copy
Range("Q6:Q2500").PasteSpecial (xlPasteAll)
Range("Q6:Q2500").PasteSpecial xlPasteValues

End Sub

When I run this macro it inserts the formulas as intended. But when I try to paste values only I get the first value repeated till Q2500 . I think it's because the formula update is to slow.

I saw another thread on Stack but the answer was to convert the formula into a VBA function. I don't know how to convert this formula.

You paste the content of Q6 twice instead of copying the values of the whole column.

Range("Q6").Formula = "=IF(INDIRECT(""A""&ROW())="""","""",CONCATENATE(INDIRECT(""A""&ROW()),""/"",INDIRECT(""B""&ROW()),""/"",INDIRECT(""E""&ROW()),""/"",INDIRECT(""P""&ROW())))"
Range("Q6").Copy
Range("Q6:Q2500").PasteSpecial (xlPasteAll)

If Application.CalculationState = xlDone Then
    Range("Q6:Q2500").Copy
    Range("Q6:Q2500").PasteSpecial xlPasteValues
End If

You are converting before calculation is completed which is causing the problem.

However you are first placing the Formula to the Cell and then copying the Value into the Cell . This can be shortened to letting VBA calculate the Value and place it into the Cell . Its advised to not make use of .Copy and .Paste if it can be avoided.

See example:

Sub JoinStrings()
    Dim cell As Range
    Dim strJoin As String

    With Worksheets("Sheet1")
        For Each cell In .Range("Q6:Q2500")
            If .Range(cell.Offset(0, -16).Value) <> "" Then
                strJoin = .Range(cell.Offset(0, -16).Value).Value & "/"
                strJoin = strJoin & .Range(cell.Offset(0, -15).Value).Value & "/"
                strJoin = strJoin & .Range(cell.Offset(0, -12).Value).Value & "/"
                strJoin = strJoin & .Range(cell.Offset(0, -1).Value).Value
                cell.Value = strJoin
            End If
        Next
    End With
End Sub

For anyone searching this. In general to value paste efficiently use the below code.

With Selection
.Value = .Value
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM