我正在处理一个链接到位于网络路径上的Excel工作簿的UserForm。在笔记本中我有一个名为Source的表。该表包含ID和源名称。在UserForm中,有一个按钮可以向表中添加新的源。我目前的VBA如下:
Private Sub bFinishAdd_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim lr As Long
Set wb = Workbooks.Open("\\datapath\datasub1\datasub2\filename.xlsx")
Set ws = wb.Worksheets("Source")
Set rng = ws.Range("Source[Source]")
If tbNewSourceName <> "" Then
If Application.WorksheetFunction.CountIf(rng, tbNewSourceName) > 0 Then
MsgBox "Source System already exists!"
lbSourceSystems.Enabled = True
bAddSource.Enabled = True
frameAddSource.Enabled = False
lblNewSourceName.Enabled = False
bFinishAdd.Enabled = False
bCancelAdd.Enabled = False
tbNewSourceName = ""
tbNewSourceName.Enabled = False
tbNewSourceName.BorderStyle = fmBorderStyleNone
Exit Sub
Else
lr = ws.Cells(Rows.Count, 1).End(xlUp).Row
ws.Cells(lr + 1, 1) = lr - 1 + 1000
ws.Cells(lr + 1, 2) = tbNewSourceName
End If
End If
End Sub
添加新来源会触发错误&#34;&#39; _Default&#39;如果对象&#39;范围&#39;失败&#34 ;. Excel只是崩溃,我无法调试,但我知道错误是由:
引起的 ws.Cells(lr + 1, 1) = lr - 1 + 1000
ws.Cells(lr + 1, 2) = tbNewSourceName
但是,我不明白为什么我收到错误或如何修复错误。有什么想法吗?
答案 0 :(得分:1)
显然使用默认方法在某处出错了。您无法将文本框分配给单元格。所以要明确。尝试:
<div>
<img src="https://www.python.org/static/opengraph-icon-200x200.png" />
</div>
答案 1 :(得分:1)
我发现我尝试添加的同一个表被列为UserForm上ListBox的RowSource。我更新了代码以删除RowSource,然后再添加并添加回来。
lbSourceSystems.RowSource = ""
lr = ws.Cells(Rows.Count, 1).End(xlUp).Row
ws.Cells(lr + 1, 1).Value = lr - 1 + 1000
ws.Cells(lr + 1, 2).Value = tbNewSourceName.Text
lbSourceSystems.RowSource = ("'filename.xlsx'!SourceSystems")