我正在VBA中从事项目工作,我想从数据集中了解最受评论的产品是什么 我尝试了以下方法:
Private Sub CommandButton1_Click()
Dim i As Long, Ligne As Long
Dim BCP As Workbook
Dim fd As FileDialog, CheminBCP$
dossierMacro = Left(ThisWorkbook.FullName, InStr(ThisWorkbook.FullName, ThisWorkbook.Name) - 1)
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Title = "Choisir Base de données "
.InitialFileName = dossierMacro
If .Show = -1 Then
CheminBCP = fd.SelectedItems(1)
End If
End With
Set fd = Nothing
Set BCP = Workbooks.Open(CheminBCP)
Ligne = BCP.Sheets(1).Range("C" & Rows.Count).End(xlUp).Row
For i = 2 To Ligne
a = Application.WorksheetFunction.Count(Range("A" & i))
Next
MsgBox a
b = WorksheetFunction.Max(a)
MsgBox b
End Sub
我尝试了以下代码:
首先:我选择要处理的文件
第二个:变量Ligne指示最后一行的号码
然后:我计算重复次数
然后:我将变量b设为a最多,成为评论最多的
但是变量a和b的问题我都是0。
我不是问题出在我的Count函数中
希望有人可以帮助我,谢谢
答案 0 :(得分:0)
假设您的代码Ligne
等于10
,
For i = 2 To Ligne
a = Application.WorksheetFunction.Count(Range("A" & i))
Next
MsgBox a
b = WorksheetFunction.Max(a)
MsgBox b
...会这样做:
2
到10
,它用a
,.Count
,... {{ 1}}。函数Range("A2")
(选中documentation here)对包含某个范围内数值的像元数进行计数。例如,如果您说Range("A3")
,并且有Range("A10")
,Count
和.Count(Range("A2:A4")
,则将得到A2="b"
(单元格A3=4
)。由于循环始终会重新定义A4="c3"
,因此退出循环1
时,将是A2
范围内的数字单元格数(即a
。它可以是{{1} }或a
,显然您是Range("A10")
。Range("A" & Ligne)
的{{1}}。由于1
是0
,因此0
也必定是.Max()
(更一般地说,对于您编写代码的方式,a
总是会等于a
)。如果没有数据样本,我们将无济于事。但是,如果我假设您有一个像这样的数据列表:
0
..那么您可以像这样设计循环:
b
使用上面的代码和我发布的示例数据,您将获得0
= 4和b
= Android。
答案 1 :(得分:0)
尽管@Matteo NNZ很好地解释了代码出了问题的地方(请通过解释进行解释)。内联代码的另一种方法
Private Sub CommandButton1_Click()
Dim i As Long, Ligne As Long
Dim BCP As Workbook
Dim fd As FileDialog, CheminBCP$
Dim Rng As Range, Mx As Long, Cnt As Long
Dim ProductX As String, ProductY As String
dossierMacro = Left(ThisWorkbook.FullName, InStr(ThisWorkbook.FullName, ThisWorkbook.Name) - 1)
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Title = "Choisir Base de données "
.InitialFileName = dossierMacro
If .Show = -1 Then
CheminBCP = fd.SelectedItems(1)
End If
End With
Set fd = Nothing
Set BCP = Workbooks.Open(CheminBCP)
Ligne = BCP.Sheets(1).Range("C" & Rows.Count).End(xlUp).Row
Mx = 0
ProductY = ""
For i = 2 To Ligne
ProductX = BCP.Sheets(1).Cells(i, 1).Value
'Test if ProductX is unique i.e. not counted before
If i > 2 Then
Set Rng = BCP.Sheets(1).Range("A2:A" & i - 1).Find(What:=ProductX, LookIn:=xlValues)
End If
If Rng Is Nothing Then ' only when Unique product is found
'would work only if all the values in the Column A is String
Cnt = Application.WorksheetFunction.CountIf(Range("A2:A" & Ligne), ProductX)
If Cnt > Mx Then
Mx = Cnt
ProductY = ProductX
End If
End If
Next i
MsgBox ProductY & " appeared Max " & Mx & " times in the list"
End Sub