我可以使用下面的代码将单元格值复制到多列listbox1。问题是它只在Sheet3处于活动状态时才有效,否则我在Listbox1中什么都没有。
我尝试了Range.cells(cell.offset...)
,但它也无效。任何帮助将不胜感激。
With Me.ListBox1
.Clear
.ColumnCount = 6
.ColumnWidths = "20;60;260;80;50;50"
For Each cell In ActiveWorkbook.Sheets(Sheet3.Name).Range(Cells(13, cbPartList.ListIndex + 7), Cells(txIndex.text, cbPartList.ListIndex + 7))
If cell = "O" Or cell = "o" Then
.AddItem cell
.List(.ListCount - 1, 1) = cell.Offset(0, 1)
.List(.ListCount - 1, 2) = cell.Offset(0, 4)
.List(.ListCount - 1, 3) = cell.Offset(0, 2)
.List(.ListCount - 1, 4) = cell.Offset(0, 7)
.List(.ListCount - 1, 5) = cell.Offset(0, 9)
End If
Next
End With
答案 0 :(得分:1)
此代码存在几个问题。这条线
For Each cell In ActiveWorkbook.Sheets(Sheet3.Name).Range(Cells(13, cbPartList.ListIndex + 7), Cells(txIndex.text, cbPartList.ListIndex + 7))
分解如下
Sheet3
ActiveWorkbook` 中ActiveWorkbook.Sheets(Sheet3.Name)1 is the code name of a sheet in the workbook containing the VBa code that is executing. It may or may not be valid for the
Cells(...)
是指ActiveWorkbook
。只有当Activeworkbook
是包含代码的图书并且Sheet3
处于有效状态
你应该;
声明并设置工作簿变量
Dim wb as Workbook
设置对特定工作簿的引用。此可能是活动图书
Set wb = ActiveWorkbook
或特定工作簿
Set wb = Workbooks("Name of Workbook")
然后声明工作表变量,并将其设置为特定工作表
Dim ws as Worksheet
Set ws = wb.WorkSheets("SheetName")
(如果您特别想使用CodeName
,这将会有所不同)
声明循环时,请使用
Dim Cell as Range
With ws
For each Cell in .Range(.Cells(...), .Cells(...))
请注意.
。这些引用With
块对象