我有一个命名范围lstVendors,引用:= OFFSET(数据!$ W $ 2,0,0,COUNTA(数据!$ W $ 2:$ W $ 400),1)。我希望在工作簿打开时填充此范围。我有以下代码:
Private Sub Workbook_Open()
Application.WindowState = xlMaximized
Dim rslt()
Dim i As Integer
Dim n As Integer
Dim startRng As Range
Dim DropDown1 As DropDown
ThisWorkbook.Sheets("Dashboard").Shapes("TextBox 6").Visible = False
' Range("lstVendors").Offset(0, 0).Value = "Please Select..."
' Set DropDown1 = ThisWorkbook.Sheets("Dashboard").DropDowns("Drop Down 1")
' DropDown1.Value = 1
On Error Resume Next
If Not IsError(Range("lstVendors")) Then
Range("lstVendors").ClearContents
End If
On Error GoTo 0
rslt = Application.Run("SQLite_Query", "path/to/my/sqlite", "SELECT PROGRAM_ID FROM VENDOR;")
Set startRng = Range("lstVendors")
i = 0
For n = 2 To UBound(rslt)
Range("lstVendors").Offset(i, 0).Value = rslt(n)(0)
i = i + 1
Next n
End Sub
Set startRng = Range(“lstVendors”)出错。我知道这是因为当我尝试设置它时,范围内没有任何内容,因为如果我将一个条目放入命名范围,该集合可行,但是,我需要在每次打开时将sqlite查询填充为数据变化。
任何建议都非常感谢。
答案 0 :(得分:1)
试试这个。清除内容后,您的动态范围无法评估。为了避免这种情况,可能有多种方法,但很容易简单地对startRange
变量进行硬编码,使其始终指向Data!$W$2
地址,这是(或者更确切地说,将成为){的第一个单元格{1}}范围。
lstVendors
答案 1 :(得分:0)
感谢您的建议。以下是我为了解决问题而最终做的事情。它涉及添加我未指定的东西在我的原始问题中是可以的,所以如果我所做的不是一个选项,大卫的答案是很好的。我首先使用“请选择...”和“全部”填充我命名范围中的前两个单元格。在Sub Workbook_Open()中,我们这样做:
Private Sub Workbook_Open()
Application.WindowState = xlMaximized
Dim rslt()
Dim i As Integer
Dim n As Integer
Dim startRng As Range
Dim DropDown1 As DropDown
' Disable our not found message
ThisWorkbook.Sheets("Dashboard").Shapes("TextBox 6").Visible = False
' Set our start range to our named range
Set startRng = Range("lstVendors")
' Grab all vendor names
rslt = Application.Run("SQLite_Query", "path/to/my/sqlite", "SELECT PROGRAM_ID FROM VENDOR;")
' Print result. Skip first two rows as constants "Please Select..." and "All" are populated there
i = 2
For n = 2 To UBound(rslt)
startRng.Offset(i, 0).Value = rslt(n)(0)
i = i + 1
Next n
End Sub
然后我们将创建Sub Workbook_BeforeClose:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
' Disable the save changes dialog. This workbook will be locked up for display only. No need to confuse the user.
Application.DisplayAlerts = False
' Clear everything below the "Please Select..." and "All" cells in the named range
On Error Resume Next
Range("lstVendors").Offset(2, 0).ClearContents
On Error GoTo 0
' Save the changes to the named range
ThisWorkbook.Save
Application.DisplayAlerts = True
End Sub
此信息将填充下拉列表,因此请将Select Select和All硬编码到指定范围内对我来说是可以接受的。如果该规定对将来查看此内容的其他人不起作用,请使用David的建议!再次感谢!