我有一个函数可以解析文本和单元格值,以便为HTML表格创建代码。
这是我的代码:
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
问题是我想在两个范围内循环。范围称为Rng1
和Rng2
。我想组合:Rng“和循环标识符j
来制作Rng1.Cells(i,1)
,但由于它位于该对象的中间,我不知道如何组合它。
对此有何帮助?
答案 0 :(得分:0)
我在代码中添加了一个if语句,使其引用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
答案 1 :(得分:0)
我想我现在正在尝试做什么。您可以创建范围对象数组:
dim rangeArray
set rangeArray = array(Rng1, Rng2)
并像这样使用它:
retVal = retVal & "<td>" & rangeArray(j).Cells(i, 1) & "</td>"