|
附件中的custKey变量,定义后点单元要运行不了,定义后又提示类型不匹配,如何处理或者哪修改?
请大神帮忙看看。
附件的代码如下:
Option Explicit
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Me.Columns("C")) Is Nothing And Target.Value = "点击生成" Then
Dim wsSource As Worksheet, wsTarget As Worksheet
Dim newSheet As Worksheet
Dim lastRowSrc As Long, i As Long, j As Long, k As Long
Dim dictType As Object, dictCustomer As Object
Set dictType = CreateObject("Scripting.Dictionary")
Set dictCustomer = CreateObject("Scripting.Dictionary")
' 设置数据源和目标工作表引用
Set wsSource = ThisWorkbook.Worksheets("目录")
Set wsTarget = ThisWorkbook.Worksheets("数据源")
Dim clickedType As String
Dim sumCoun As Long
clickedType = wsSource.Cells(Target.Row, 2).Value ' 获取点击行的类型
sumCoun = wsSource.Cells(Target.Row, 4).Value
' 获取数据区域的最后一行
lastRowSrc = wsTarget.Cells(wsTarget.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRowSrc ' 遍历目标数据
Dim typeVal As String
Dim customerVal As String
Dim qty As Double
typeVal = wsTarget.Cells(i, 3).Value ' 数据源 C列科目
customerVal = Trim(wsTarget.Cells(i, 4).Value) ' 数据源 B列项目
qty = wsTarget.Cells(i, "sumCoun").Value ' 数据源 求和列的数量
If typeVal = clickedType And customerVal <> "" Then
If Not dictType.exists(typeVal) Then
Set dictType(typeVal) = New Scripting.Dictionary
End If
If Not dictType(typeVal).exists(customerVal) Then
dictType(typeVal).Add customerVal, qty
Else
dictType(typeVal)(customerVal) = dictType(typeVal)(customerVal) + qty
End If
End If
Next i
' 创建新工作表并写入汇总结果
On Error Resume Next
Set newSheet = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
newSheet.Name = clickedType
On Error GoTo 0
If Err.Number <> 0 Then
MsgBox "无法创建名为 '" & clickedType & "' 的工作表,因为它已经存在或名称不符合Excel的工作表命名规则。"
Err.Clear
Exit Sub
End If
newSheet.Range("A1:B1") = Array("客商", "期末余额") ' 设置新工作表的表头
j = 2
Dim custKey As Variant
For Each custKey In dictType(clickedType).Keys
newSheet.Cells(j, 1).Value = custKey
newSheet.Cells(j, 2).Value = dictType(clickedType)(custKey)
j = j + 1
Next custKey
Cancel = True ' 取消双击操作的默认行为(例如选中或编辑)
End If
End Sub
|
|