我一直在尝试将一些代码转换为html表,该代码应该将工作表中的范围转换为html表。它似乎工作得很好。但有时会多次填充行,这意味着在活动工作表中只能复制2行,但html表输出包含html代码表行中标题和数据行的重复。有趣的是,如果我在计算行和列之后设置一个断点,那么bug似乎不常发生。我真的迷失在这里可以有人对此有所了解吗?
我使用以下代码:
' establish number of columns and rows to send
Report.Activate 'this is a worksheet object
NumbofRows = Report.Range("A1", Range("A1").End(xlDown)).Rows.Count
NumbofCols = Report.Range("A1", Range("A1").End(xlToRight)).Columns.Count
' Populate headers
TableHeaders = "<table> <tr>"
For i = 1 To NumbofCols
TableHeaders = TableHeaders & "<th>" & Report.Cells(1, i) & "</th>"
Next i
TableHeaders = TableHeaders & "</tr>"
' populate response rows
For y = 2 To NumbofRows
If WorksheetFunction.IsEven(y) Then
Style = "style= " & Chr(39) & "background:#CCEBFF" & Chr(39)
Else
Style = "style= " & Chr(39) & "background:#E6F5FF" & Chr(39)
End If
' loop through cells on the current row and add them to the table
TableRows = TableRows & "<tr " & Style & ">"
For x = 1 To NumbofCols
TableRows = TableRows & "<td>" & Report.Cells(y, x) & "</td>"
Next x
TableRows = TableRows & "</tr>"
Next y
' close table tag
TableRows = TableRows & "</table> <br> <br>"
'stick them together
ResponseTable = TableHeaders & TableRows
答案 0 :(得分:0)
依赖于 ActiveSheet 时的常见错误是指定单元格范围的父级,而未能在标记范围的开始和停止的单元格上指定相同的父级。例如:
NumbofRows = Report.Range("A1", Report.Range("A1").End(xlDown)).Rows.Count
NumbofCols = Report.Range("A1", Report.Range("A1").End(xlToRight)).Columns.Count
我会将整段代码包装到With ... End With
代码块中,并使用.
为每个单元格/范围定义添加前缀。 .
指定每个引用属于使用With ... End With
代码定义的父级。
With Report
' establish number of columns and rows to send
'.Activate 'NOT NECESSARY
NumbofRows = .Range("A1", .Range("A1").End(xlDown)).Rows.Count
NumbofCols = .Range("A1", .Range("A1").End(xlToRight)).Columns.Count
' Populate headers
TableHeaders = "<table> <tr>"
For i = 1 To NumbofCols
TableHeaders = TableHeaders & "<th>" & .Cells(1, i) & "</th>"
Next i
TableHeaders = TableHeaders & "</tr>"
' populate response rows
For y = 2 To NumbofRows
If CBool(y Mod 2) Then
Style = "style= " & Chr(39) & "background:#E6F5FF" & Chr(39)
Else
Style = "style= " & Chr(39) & "background:#CCEBFF" & Chr(39)
End If
' loop through cells on the current row and add them to the table
TableRows = TableRows & "<tr " & Style & ">"
For x = 1 To NumbofCols
TableRows = TableRows & "<td>" & .Cells(y, x) & "</td>"
Next x
TableRows = TableRows & "</tr>"
Next y
' close table tag
TableRows = TableRows & "</table> <br/> <br/>"
'stick them together
ResponseTable = TableHeaders & TableRows
End With
这应该处理错误行为,并使您无需依赖 ActiveSheet 来获取单元格/范围引用的父级。
使用Report.Range("A1").End(xlDown)
来定义范围的范围有点麻烦。除了标题行之外的表中没有行,您将定义工作表底部的所有行。