Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 89289

Excel VBA: Collect data from cells and assign to a range. How to avoid vba do text to column automatically?

$
0
0

I want to collect data from a large worksheet and paste to a target range.

The data mix with number and number like string (ex:"0050").

I try to use variant array to store the data and assign to a series of cells.

Here is the sample code:

Dim z() As Variant
Dim i As Integer
ReDim z(1 To 3, 1 To 1)
With ThisWorkbook.Sheets(1)

    .Cells(1, 1) = "'"& "0050"'content from cell A, could be number or number like string.
    .Cells(3, 1) = 20           'content from cell B, could be number or number like string.
    .Cells(5, 1) = "'"& "040"'content from cell C, could be number or number like string.

    For i = 1 To 3
        z(i, 1) = .Cells(1 + (i - 1) * 2, 1)
    Next

    .Cells(1, 2).Resize(3, 1) = z

End With

Excel automatically change the string "0050" to a number format so that the value in cell(1,2) will be 50, not "0050".

I want the cell's format to be the same as it originally be but I don't know each cell's format in advance.

I can use loop assign each cell to another but the running speed will be slow:

Dim z() As Variant
Dim i As Integer
ReDim z(1 To 3, 1 To 1)
With ThisWorkbook.Sheets(1)

    .Cells(1, 1) = "'"& "0050"'content from cell A, could be number or number like string.
    .Cells(3, 1) = 20           'content from cell B, could be number or number like string.
    .Cells(5, 1) = "'"& "040"'content from cell C, could be number or number like string.

    For i = 1 To 3
        .Cells(i, 2) = .Cells(1 + (i - 1) * 2, 1)
    Next

End With

Is there a way to avoid Excel automatically change the string to number?

Hope I describe my question clearly.

Thanks in advance.


Viewing all articles
Browse latest Browse all 89289


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>