Monday, September 27, 2010

Copy Range Values to VBA

Not sure how useful this is, but sometimes I need to fill in a spreadsheet with some default values. So I wrote this code to take a spreadsheet I manually filled out and write the code needed to put those values back into a spreadsheet. This just loops through all the selected cells and makes VBA code for building those values back:

Function CodeRangeInVBA(TheRange As Range) As String
Dim Result As String
Dim Cr As Range
For Each Cr In TheRange
If Result <> "" Then Result = Result & Chr(10)
Result = Result & "Range(" & Chr(34) & Cr.AddressLocal & Chr(34) & ").Value = " & Chr(34) & CStr(Cr.Value) & Chr(34)
Next Cr
CodeRangeInVBA = Result
End Function