简体   繁体   中英

How to use VBA to combine 3 cells from one sheet into 1 cell in another sheet?

So I've been doing this process manually but I need to automate it with a macro but using this formula:

='Sheet1'!C2&"|"&'Sheet1'!D2&"|CM"&'Sheet1'!H2

I need to pull 3 cells of data into one cell in Sheet2 separated by a break. As well as doing that for the next 96 lines. So far I've tried to do it this way:

Dim SheetName As Worksheet1
    Set SheetName = Worksheets("Sheet1")
    Worksheets("Sheet2").Range("B2:B97").Formula = Worksheets(2).Range("C2:C97") & "|" & Worksheets(2).Range("D2:D97") & "|CM" & Worksheets(2).Range("H2:H70")

Worksheets(2) = "Sheet1"

Keep getting a object defined error.
but I keep getting a

Like this, making sure to double up quotes in the formula:

Worksheets("Sheet2").Range("B2:B97").Formula = "='Sheet1'!C2&""|""&'Sheet1'!D2&""|CM""&'Sheet1'!H2"

Remove the lines

Dim SheetName As Worksheet1
Set SheetName = Worksheets("Sheet1")
...
Worksheets(2) = "Sheet1"

as they don't make any sense.

Here is an example of how you would do this where all the ranges are on the same sheet. You pretty much just need to nest your existing formula here and double quote your bar separator

Sub try()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Range("D1:D3").Formula = "=A1 & ""|"" & B1 & ""|"" & C1"

End Sub

在此处输入图像描述

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