2017-01-02 56 views
-1

我有一個輸入框,用戶正在輸入一個值。我想獲取用戶輸入的值並將其添加到正在從記錄集讀取的值中。我已經嘗試過這種語法,它不會爲我引發錯誤,但問題是,該值未被添加到記錄集的值中。爲了進行簡單的加法計算,我應該改變什麼?添加值從記錄集+值從輸入框通過VBA

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)獲取userinput爲值2
2)閱讀來自現場的數值總計
3)向Excel寫入總計值+值2

在那裏我看到用編輯#2
鏈接兩個If Not EOFWhile Not EOF

Looping DAO Recordsets

+1

很多你的代碼是沒有感。 'row = 1',打開數據集,'row = row + 1'沒用。那麼'如果不是EOF,那麼不是EOF'; if語句是無用的冗餘。如果你在Eof,那麼這段時間不會執行,所以根本沒有必要。目前還不清楚你實際想要做什麼。 –

+0

@KenWhite - 我想要1)獲取用戶輸入的值2 - 2)從字段Total中讀取值,3)向Excel寫入總值+值2 –

+0

@KenWhite - 迴應您的?關於使用If ... EOF和While ... EOF - 就我的理解而言,您將首先執行if ... EOF以驗證ExportRecordSet具有記錄。 - > While ... EOF遍歷記錄,如果達到ExportRecordSet的末尾,則此方法將返回true並離開while循環。我用這個作爲語法的基礎,這是關於如何編碼的標記? http://www.accessallinone.com/looping-through-a-recordset/ –

回答

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