2017-03-31 191 views
0

我想用VBA在Excel中創建一個表格,但我被卡在代碼中。我需要找到代碼來使用VBA表單將數據輸入到我的工作表中。這裏是我使用的代碼,但不起作用。使用VBA在excel中創建表格

Private Sub cmdAdd_Click() 

Dim LastRow As Range 
Dim DPDIAdhocRequestTable As ListObject 


With LastRow 

    Cells(1, 2) = RequesterName.Value 
    Cells(1, 3) = RequesterPhoneNumber.Value 
    Cells(1, 4) = RequesterBureau.Value 
    Cells(1, 5) = DateRequestMade.Value 
    Cells(1, 6) = DateRequestDue.Value 
    Cells(1, 7) = PurposeofRequest.Value 
    Cells(1, 8) = ExpectedDataSaurce.Value 
    Cells(1, 9) = Timeperiodofdatarequested.Value 
    Cells(1, 10) = ReoccuringRequest.Value 
    Cells(1, 11) = RequestNumber.Value 
    Cells(1, 12) = AnalystAssigned.Value 
    Cells(1, 13) = AnalystEstimatedDueDate.Value 
    Cells(1, 14) = AnalystCompletedDate.Value 
    Cells(1, 15) = SupervisiorName.Value 

End With 


End Sub 

你能幫我弄清楚輸入命令的正確代碼嗎?

非常感謝你的幫助。

+1

'但不work..' - 什麼,具體而言,是不是工作? –

+0

'Cells(x,y).Value = ObjectName.Value'您是否嘗試過這種語法? –

+0

你可能想糾正'SupervisiorName'的拼寫 - 雖然不是一個錯誤,但會讓我更加惱火。 :) –

回答

0

第一個問題是,你已經創建了一個名爲RangeLastRow尚未分配什麼的。

'Declaration 
Dim LastRow As Range 
'Assigns the last row based on the last item in Column A 
Set LastRow = Range("A" & Rows.Count).End(xlUp).Row 
With LastRow 
    ... 
End With 

第二個問題是With LastRow塊中的次要語法錯誤。

With LastRow 
     Cells(x,y).Value = "Foo" 
End With 

應該

With LastRow 
    .Cells(x,y).Value = "Foo" 
End With 

基本上是相同的話說LastRow.Cells(x,y).Value = "Foo"。沒有「。」在Cells()前VBA不會對With應用到該對象,並承擔你的意思ActiveSheet.Cells()

+0

他們的'With'語句不會對其內部的任何內容產生任何影響,使用它當前寫入的方式 – Tom

+0

@Tom很好的捕獲,更新它的方式。 –

1

正如@Adam說 - 你已經創建LASTROW,而不是它分配給什麼。
我猜這是你想要粘貼數據的下一行,所以它應該是一個Long保存行號而不是對單元格的實際引用。

在下面你的代碼有資格表單控件加入Me.,例如Me.RequesterName.Value
https://msdn.microsoft.com/en-us/library/office/gg251792.aspx

Private Sub cmdAdd_Click() 

    Dim wrkSht As Worksheet 
    Dim LastRow As Long 

    'The sheet you want the data to go into. 
    Set wrkSht = ThisWorkbook.Worksheets("Sheet1") 

    'You're after the last row number, rather than referencing the range so LastRow is a Long. 
    'This looks for the last cell containing data in column A (the 1 in 'Cells(...)'). 
    LastRow = wrkSht.Cells(Rows.Count, 1).End(xlUp).Row + 1 

    'With... End With block. Cells is preceded by a '.' notation - indicating it's referencing the 'With wkrSht'# 
    'https://msdn.microsoft.com/en-us/library/wc500chb.aspx 
    With wrkSht 

     'Using LastRow as row number in cell reference. 
     .Cells(LastRow, 2) = RequesterName.Value 

     'Before adding dates to the sheet you might want to check that the 
     'user entered a date and not rubbish. 
     .Cells(LastRow, 5) = DateRequestMade.Value 
     'You could use CDATE to force it to a date - will try and coerce the entered text into a date. 
     'Note - 1 will be changed to 01/01/1900 (so will need to add extra code to check it really is a date). 
     .Cells(LastRow, 5) = CDate(DateRequestMade.Value) 

    End With 

End Sub