简体   繁体   中英

MergeCells with defined range (Run-time error 1004)

I'm trying to merge cells based on two cell values that change according to user input but am having probems with the following code:

    SafB = 5 + 2 * Sheets("LinksTable").Range("X2").Value - 2 * Sheets("LinksTable").Range("W2").Value
    SafE = 5 + 2 * Sheets("LinksTable").Range("X2").Value - 1

    Set SafRB = Sheets("Report").Range("B1").Offset(SafB - 1, 0)
    Set SafRE = Sheets("Report").Range("C1").Offset(SafE - 1, 0)

    Sheets("Report").Range("SafRB:SafRE").MergeCells = True

For example, cells W2 and X2 will have values that change depending on how many metrics are selected for a given lever, in this case "Safety". So if the user selects 2 metrics for the Safety lever, W2 = 2 (number of metrics for that lever) and X2 = 2 (cumulative number of metrics in the report; safety being the first lever, the cumulative equals the total in this case).

Given the above code, SafB=5 and SafE=8. Therefore the cells I need to merge are B5:C8.

However, I get the following error message whenever I run the above code:

"Run-time error '1004': Application-defined or object-defined error".

Any help would be greatly appreciated!

You're sending a string literal, "SafRB:SafRE" as a range argument. This error means there is no such range defined on your sheet or workbook.

I think this should work. use your range variables as arguments to the Range method, like so:

Sheets("Report").Range(SafRB, SafRE).Merge

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