我正在使用Excel VBA。我试图在excel中水平循环列,直到记录集中的最后一个值。以下是我的代码。我希望它从列G开始,直到记录集中的数据。如下面的代码我将最后一列表示为X.它可能是BM / BN,但在开始时无法预测。
请帮助我找到理想的解决方案。
Set RS = 'recordset is set
If Not RS.BOF And Not RS.EOF Then
RS.MoveFirst
Do While Not RS.BOF And Not RS.EOF
Set xlApp = CreateObject("Excel.Application")
Set xlWorkbook = xlApp.Workbooks.Open(ReportTemplateDirectory & TestExcel.xlsx")
xlWorkbook.Sheets(2).Name = "Calculation"
Set ShtReport = xlApp.Workbooks(1).Sheets("Calculation")
xlApp.Workbooks(1).Sheets("Calculation").Range("G6").Value = "")
.....
..... 'Loop until the last column to be used
.....
xlApp.Workbooks(1).Sheets("Calculation").Range("X").Value = "")
RS.MoveNext
Loop
End If
答案 0 :(得分:0)
您可以通过相当简单的循环来完成此任务。我添加了一些内联注释,以注意所做的更改。
Set RS = 'recordset is set
' Not sure if you need/want the RS.BOF condition here...
If Not RS.BOF And Not RS.EOF Then
RS.MoveFirst
' Initial Excel outside of the loop.
' Otherwise you create an instance for each record entry.
Set xlApp = CreateObject("Excel.Application")
Set xlWorkbook = xlApp.Workbooks.Open(ReportTemplateDirectory & "TestExcel.xlsx")
Set ShtReport = xlWorkbook.Sheets(2)
ShtReport.Name = "Calculation"
Dim col As Integer
col = 7 ' Start on column G.
Do While Not RS.EOF
' All output will go to row 6.
ShtReport.Cells(col, 6).Value = "?" ' Put value from RS here.
RS.MoveNext
col = col + 1
Loop
' If you are done with Excel, release the resources here.
End If