[英]Loop until the last column (Horizontally) to be used
I am working on Excel VBA.我正在使用 Excel VBA。 I am trying to loop through the columns horizontally in excel as until the last value in recordset.
我试图在 excel 中水平循环列,直到记录集中的最后一个值。 Below is my code.
下面是我的代码。 As I want it to start from column G and up to data in recordset.
因为我希望它从 G 列开始直到记录集中的数据。 As in Below code I have represent last column as X .
在下面的代码中,我将最后一列表示为 X 。 It may be BM/BN but can not predict at starting.
可能是BM/BN,但在开始时无法预测。
Please help me to get the desired solution.请帮助我获得所需的解决方案。
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
You could accomplish this with a fairly straightforward loop.您可以使用一个相当简单的循环来完成此操作。 I added some inline comments to note some the changes made.
我添加了一些内联注释以记录所做的一些更改。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.