horace_vr
horace_vr

Reputation: 3166

Excel VBA - array used to process ranges changes the format of the cells

I am using an array to process the values (and texts) I have in a sheet:

Dim arr As Variant

arr = Application.ActiveSheet.UsedRange
'do stuff
Application.ActiveSheet.UsedRange = arr

However, this has a side-effect: when dumping the array back into the cells, the cells formatting is changed by Excel's default behaviour. For example, numbers stored as text which start with "0" are converted to numbers, and the "0" gets deleted. Or texts like "1-11" are converted to dates ("November 1"); and probably some others which I have not spotted yet.

If I monitor the Locals window, the strings are being preserved as strings in the array until the very moment, so it is the unloading that messes things up.

Is there a way to avoid this behavior ?

Edit: I also tried:

Application.ActiveSheet.UsedRange.Value = arr
Application.ActiveSheet.UsedRange.Value2 = arr
Application.ActiveSheet.UsedRange.text = arr

Same result for each.

Upvotes: 2

Views: 3397

Answers (2)

user12487197
user12487197

Reputation: 1

Also try

YourRangeVariable.NumberFormat = "@"

YourRange.Value=Your Array

This will convert the range to text first. Works for me when using values like 01-11 and saves having to do a loop.

Upvotes: 0

Charles Williams
Charles Williams

Reputation: 23520

You can use the valuetype option to preserve formatting etc: 11 is xlRangeValueXMLSpreadsheet

Sub CopyWithFormat()
Dim var As Variant
var = Range("A8:A11").Value(11)
Range("C8:C11").Value(11) = var
End Sub

But that will make it difficult to modify the values in the array. So its probably simplest to loop the array adding '

Sub CopyWithFormat2()
    Dim var As Variant
    Dim j As Long
    var = Range("A8:A11").Value
    For j = 1 To UBound(var)
        If VarType(var(j, 1)) = vbString Then var(j, 1) = "'" & var(j, 1)
    Next j
    Range("C8:C11").Value = var
End Sub

Upvotes: 3

Related Questions