我有一个输入框,用户正在输入一个值。我想获取用户输入的值并将其添加到从记录集中读取的值。我试过这种语法,这不会给我带来错误,但问题是,该值没有被添加到记录集的值中。为了进行简单的加法计算,我应该改变什么?
Public Function AddToValue()
Dim value2 As Variant
Dim ExportRecordSet As DAO.Recordset
Dim excelWS As Object
Dim xl As Object
Dim wb As Object
Dim TemplateWB As String
Dim row As Integer
value2 = InputBox("Enter Value To Add:", "VBA InputBox Function")
Set xl = CreateObject("Excel.Application")
TemplateWB = "C:\Test\Testwb.xlsx"
Set wb = xl.Workbooks.Add
Set excelWS = wb.Worksheets(1)
excelWS.Name = "AddedFromCode"
xl.Application.Visible = True
Set ExportRecordSet = db.OpenRecordset(" Select Total FROM localtesttable;")
If Not ExportRecordSet.EOF Then
While Not ExportRecordSet.EOF
excelWS.Cells(row, 5).Value = ExportRecordSet("Total")+value2
Wend
End If
wb.SaveAs
wb.Close
End Function
修改
根据@KenWhite的评论 - 我将在上面的语法中准确说明我想要实现的目标:
1)获取value2的输入值2)从字段中读取值总计
3)从字段total + value2中写入Excel的值
编辑#2
我看到使用If Not EOF
和While Not EOF
答案 0 :(得分:0)
您需要前进行和记录集:
Public Function AddToValue()
Dim ExportRecordSet As DAO.Recordset
Dim excelWS As Object
Dim xl As Object
Dim wb As Object
Dim TemplateWB As String
Dim row As Integer
Dim value2 As String
value2 = InputBox("Enter Value To Add:", "VBA InputBox Function")
Set xl = CreateObject("Excel.Application")
TemplateWB = "C:\Test\Testwb.xlsx"
Set wb = xl.Workbooks.Add
Set excelWS = wb.Worksheets(1)
excelWS.Name = "AddedFromCode"
xl.Application.Visible = True
Set ExportRecordSet = db.OpenRecordset("Select Total FROM localtesttable;")
' Set start row.
row = 1
While Not ExportRecordSet.EOF
excelWS.Cells(row, 5).Value = ExportRecordSet("Total") + Val(value2)
row = row + 1
ExportRecordset.MoveNext
Wend
wb.SaveAs
wb.Close
End Function