views:

156

answers:

2

I need to write the same data into two different range of cells for a VBA application that I am writing. I could of course just loop through twice and write the data, but I was hoping to do it in one pass.

This is an example of what I am doing (lot of complexity removed).

Sub WriteData()
    WriteOutDivision "Division1",10 
    WriteOutDivision "Division1",20 
End Sub

Private Sub WriteOutDivision(ByVal divisionName, ByVal rowNumber)
    Dim curSheet As Worksheet

    Set curSheet = Sheets("Company Scorecard")    

    With curSheet.Cells(rowNumber, 1)
         .value = divisionName
         .Font.Bold = True
         .InsertIndent 1
    End With
End Sub

Is there something that I can do to write to both row 10 column 1 and row 20 column 1 at the same time?

+1  A: 

Could you just pass an array of row numbers instead of one rowNumber, then in your function just loop through each element in the array (I don't remember, I haven't programed in VBA for a while)? Then you could print it to as many rows as you want.

smoore
I thought about that, I was just hoping there would be something built in that would allow this, kindof like the Resize function allows to write across many rows.
Irwin M. Fletcher
I like the idea of using an array of row numbers, or possibly even a collection (since you don't have to specify the size of the collection in code).
Ben McCormack
+7  A: 

You could define a non-contigous range and change the propeties of the range. For example:

Dim curSheet As Worksheet
Dim rngSpecial As Range

Set curSheet = Sheets("Company Scorecard")
Set rngSpecial = curSheet.Range("A1,A3")
rngSpecial.Value = "Whatever"

Will write "Whatever" in A1 and A3.

Wilhelm