我有以下数组:
ID Chat nr
#N/A
126551829 33
126554922 33
126555078 33
126555079 33
126555261 33
126555278 33
126553808 34
126553820 34
126554425 35
126555786 36
126555925 36
126555944 36
126556297 37
126556298 37
126556299 37
126556300 37
126556307 37
126556320 37
126556322 37
126556323 37
126556323 37
126556323 37
126556323 37
126556325 37
126556332 37
#N/A
#N/A
#N/A
etc...
此数据可在名为“导入”的工作表中找到。在名为“仪表板”的工作表中,我有一个下拉列表,工作表的用户可以在其中选择chat nr。例如,如果用户选择36,则需要此宏的以下输出(ID):
126555786
126555925
126555944
我试图编写代码,但是我的代码返回了数组中的所有值,而不仅是带有“ 36”的值。此外,我在“导入”表中的聊天号码列中有公式。
Private Sub CommandButton2_Click()
Dim xRng As Range
Dim xLastRow As Long
Dim xLastRow2 As Long
Dim i As Integer
On Error Resume Next
Set xRng = Worksheets("Import").Range(Range("B18"))
If xRng(, 2).Value = Worksheets("Dashboard").Range("B9").Value Then
xRng.Copy Range("F6")
xLastRow = xRng.Rows.Count + 1
ActiveSheet.Range("F6:F" & xLastRow).RemoveDuplicates Columns:=1, Header:=xlNo
End If
End Sub
代码中的单元格说明:
我花了很多时间试图解决这个问题,没有任何运气...我是VBA编码的新手,但是我渴望学习。我当然会赞扬良好的答案!
答案 0 :(得分:0)
您可以尝试以下代码(现在它将首先删除以前运行的输出):
Private Sub CommandButton2_Click()
Dim xRng As Range
Dim oRng As Range ' Output range
Dim iWS As Worksheet, dWS As Worksheet
Dim ChatNr As Long
Dim i As Integer, j As Integer
Dim LastRow As Long
Set iWS = ThisWorkbook.Sheets("Import")
Set dWS = ThisWorkbook.Sheets("Dashboard")
ChatNr = dWS.Cells(9, 2) ' cell B9
Set xRng = iWS.Range(dWS.Cells(18, 2).Value) ' cell B18, assuming the array name is defined in the scope of the iWS
Set oRng = dWS.Cells(6, 6) ' output in cell F6
LastRow = dWS.Cells(dWS.Rows.Count, 6).End(xlUp).Row
' clear previous output:
If LastRow >= 6 Then
Range(dWS.Cells(6, 6), dWS.Cells(LastRow, 6)).ClearContents
End If
j = 0
For i = 1 To xRng.Rows.Count
If IsError(xRng(i, 2)) = False Then ' added check for error
If xRng(i, 2).Value = ChatNr Then
oRng.Offset(j).Value = xRng(i, 1).Value
j = j + 1
End If
End If
Next i
End Sub
答案 1 :(得分:0)
尝试以下方法。尝试任何代码之前,请确保备份了所有(关键)数据
Option Explicit
Private Sub CommandButton2_Click()
Dim i As Long, LRow As Long
Dim wb As Workbook, Import As Worksheet, Dashboard As Worksheet
Dim myArr As Variant
Set wb = ThisWorkbook
Set Import = wb.Sheets("Import")
Set Dashboard = wb.Sheets("Dashboard")
myArr = Import.Range(Dashboard.Range("B18").Value)
LRow = Dashboard.Cells(Dashboard.Rows.Count, "F").End(xlUp).Row
If LRow < 6 Then LRow = 6
For i = 1 To UBound(myArr) - 1
If myArr(i, 2) = Dashboard.Range("B9").Value Then
DashBoard.Cells(LRow, "F").Value = myArr(i, 1)
LRow = LRow + 1
End If
Next i
End Sub
修改
如何用范围填充数组
数组基本上是存储在PC内存中的表。用范围内的值填充这样的数组很有用,因为使用数组通常比使用范围对象快得多。
使用范围填充数组如下:
Dim myArr as Variant
myArr = ThisWorkbook.Sheets(1).Range("A1:B10")
数组通常以0为底,这意味着第一个索引号为0。但是,如果数组来自范围,则第一个索引号为1,因此它们是以1为底的数组。
因此,如果单元格B4
保留值Test
,则myArr(2,4)
也保留该值。
但是:
Dim myArr as Variant
myArr = ThisWorkbook.Sheets(1).Range("A2:B10")
对于上述数组,从第二行开始填充数组时,对单元格B4值的引用为myArr(2,3)
。