2017-06-06 84 views
0

這部分代碼旨在調整表格的大小,以便從用戶窗體添加新的數據輸入行。目前,當我運行的代碼,我得到:調整表格範圍

錯誤9 - 下標越界

就行了:

Set tbl1 = sht1.ListObjects("LogTable") 

這是全碼:

Private Sub CommandButton1_Click() 

'Start button 
'Log start time as the time the button is clicked 

Dim EmptyRow, LastRow As Long 
Dim sPath    As String 
Dim tbl1, tbl2   As Range 

'Find next empty row based on first column 
Set wb = ThisWorkbook 
Set sht1 = wb.Sheets("Log") 
Set tbl1 = sht1.ListObjects("LogTable") 

LastRow = sht1.Cells(sht1.Rows.Count, "A").End(xlUp).Row 
EmptyRow = LastRow + 1 

tbl1.Resize Range("A2:E" & EmptyRow) 

sht1.Cells(EmptyRow, 1).Value = Now 

感謝您的幫助!

+1

建議您沒有該名稱的表格。但表格自動調整大小。 – SJR

回答

0

試試這個代碼:

Dim tbl1 As ListObject 
Dim wb As Workbook 
Dim sht1 As Worksheet 

    Set wb = ThisWorkbook 
    Set sht1 = wb.Sheets("Log") 
    Set tbl1 = sht1.ListObjects("LogTable") 

    tbl1.ListRows.Add 

請注意:

你的代碼中包含不正確的聲明:EmptyRow和TBL1被desclared爲Variant,這是不是你打算什麼(似乎)。這是一種常見的VBA錯誤 - 假設類型聲明適用於行中的所有變量。不是。避免它的最簡單方法是每行總是聲明一個變量。

此外,tbl1和tbl2應聲明爲表(ListObject),而不是範圍。