2014-03-05 233 views
0

我有一個函數可以解析文本和單元格的值,爲HTML表格創建代碼。Excel範圍循環變量的名稱

這裏是我的代碼:

Function Html(Rng1 As Range, Rng2 As Range, Head As Boolean) As String 
' this function will take columns of data and properly format them for html table 
Dim retVal As String 
Dim i, j, p As Integer 
p = 1 
'if ranges doesn't contains one column and same rows count - return #VALUE error 
If Rng1.Rows.count <> Rng2.Rows.count Or _ 
    Rng1.Columns.count <> 1 Or Rng2.Columns.count <> 1 Then 
    Html = CVErr(xlErrValue) 
    Exit Function 
End If 

retVal = "" 

For j = 1 To 2 

If Head = True Then 
retVal = retVal & "<th>" & Rng1.Cells(1, j)& "</th>" 
    If j = 2 Then 
    retVal = retVal & "<th>" & Rng2.Cells(1, j) & "</th>" 
    End If 
p = 2 
End If 

retVal = retVal & "<tr>" 

For i = p To Rng1.Rows.count 
    retVal = retVal & "<td>" & Rng & j & .Cells(i, 1) & "</td>" 

Next i 

retVal = retVal & "</tr>" 
Next j 


Html = "<table>" & retVal & "</table>" 
End Function 

問題是我通過兩個範圍要循環。範圍被稱爲Rng1Rng2。我想結合:?RNG」和循環標識符j使Rng1.Cells(i,1)但因爲它是在該對象的中間我不知道如何將它結合

任何幫助

+0

你試圖把並排的兩個範圍的部分,在一個HTML表?換句話說 - 你想要逐行處理它們嗎? – Floris

+0

是的,兩行數據是我之後的 – Crimpy

回答

0

我想我明白你的意思試圖現在做。您可以創建範圍對象的數組:

dim rangeArray 
set rangeArray = array(Rng1, Rng2) 

,並使用它像這樣:

retVal = retVal & "<td>" & rangeArray(j).Cells(i, 1) & "</td>" 
+1

這是一個好方法...謝謝!總是希望依靠我的代碼。 – Crimpy

0

我增加了一個如果語句插入代碼,使其指RNG2,它導致了正確的輸出。

但是,如果任何人都可以告訴我怎麼一個對象,將是有益的內結合。

Function Html(Rng1 As Range, Rng2 As Range, Head As Boolean) As String 
' this function will take columns of data and properly format them for highcharts scatter pairs 
Dim retVal As String 
Dim i, j, p As Integer 
p = 1 
'if ranges doesn't contains one column and same rows count - return #VALUE error 
If Rng1.Rows.count <> Rng2.Rows.count Or _ 
    Rng1.Columns.count <> 1 Or Rng2.Columns.count <> 1 Then 
    Html = CVErr(xlErrValue) 
    Exit Function 
End If 

retVal = "" 

For j = 1 To 2 

If Head = True Then 
retVal = retVal & "<th>" & Rng1.Cells(1, 1) & "</th>" 
    If j = 2 Then 
    retVal = retVal & "<th>" & Rng2.Cells(1, 1) & "</th>" 
    End If 
p = 2 
End If 

retVal = retVal & "<tr>" 

For i = p To Rng1.Rows.count 
    retVal = retVal & "<td>" & Rng1.Cells(i, 1) & "</td>" 
    If j = 2 Then 
    retVal = retVal & "<td>" & Rng2.Cells(i, 1) & "</td>" 
    End If 
Next i 

retVal = retVal & "</tr>" 
Next j 

'remove last comma 
If retVal <> "" Then retVal = Left(retVal, Len(retVal) - 1) 

Html = "<table>" & retVal & "</table>" 
End Function