查找匹配的VBA行号

如何解决查找匹配的VBA行号

在工作表中,我有一个名称列表,在另一列中,有一个与其相关的数量。我需要在另一张纸的一栏中写上这些名称,而不必重复。当名称重复时,我还需要将金额相加。 例如:

XXXX 20
YYYY 30
XXXX 10

我的结果应该是

XXXX 30
YYYY 30

我正在做一个for循环来遍历名称,如果我没有在结果列中写该名称,我会写它。如果我已经写过,则必须留在同一行并进行金额的总和。 问题是我尝试使用Range.Find,但即使名称已经写好,它也始终返回Nothing。

代码如下:

Sub CommandButton1_Click()

Dim rif_reg As Integer
Dim rif_col As Integer
Dim riga_vuota As Integer
Dim rif_foglio As Integer
Dim rowNum As Range

For Each area In Worksheets("XXX").Range("C15:C26,C30:C41,C44:C55,C58:C69").Areas 'more than 1 selected area
    For Each cell In area 'loop through each cell in the selected range
        If IsEmpty(cell) = False Then
            If IsNumeric(cell) = False Then
                If Range("A61:A74").Find(What:=cell.Value2,LookIn:=xlValues,LookAt:=xlWhole,MatchCase:=True) is Nothing Then 'search if the name has not being inserted yet
                    Cells(rif_rig + 61,rif_col + 1) = cell 'Nominativo
                    Cells(rif_rig + 61,rif_col + 7) = Worksheets("XXX").Cells(area.Cells(1).Row,rif_col + 1).Value2 'Ruolo
                    Cells(rif_rig + 61,rif_col + 11) = (Worksheets("XXX").Cells(cell.Row,rif_col + 5).Value2 * Worksheets("YYY").Cells(rif_foglio + 32,rif_col + 2)) 'Quota Lordo
                    rif_rig = rif_rig + 1
                Else
                    Set rowNum = Range("A61:A74").Find(What:=cell.Value2,MatchCase:=True)
                    Cells(rowNum.Row,rif_col + 11) = (Cells(rowNum.Row,rif_col + 11) + Worksheets("XXX").Cells(cell.Row,rif_col + 2)) 'Quota Lordo
                    If Cells(rowNum.Row,rif_col + 7) <> Worksheets("XXX").Cells(area.Cells(1).Row,rif_col + 1).Value2 Then
                        Cells(rowNum.Row,rif_col + 7) = Cells(rowNum.Row,rif_col + 8) & "," & Worksheets("XXX").Cells(area.Cells(1).Row,rif_col + 1).Value2 'Ruolo
                    Else
                        Cells(rowNum.Row,rif_col + 1).Value2 'Ruolo
                    End If
                End If
            Else
            End If
        Else
        End If
    Next
areaCount = areaCount + 1
Next

由于此操作无效,因此我尝试使用Application.Match,但这不能为我提供正确的行号

Sub CommandButton1_Click()

Dim rif_reg As Integer
Dim rif_col As Integer
Dim riga_vuota As Integer
Dim rif_foglio As Integer
Dim rowNum As Long

For Each area In Worksheets("XXX").Range("C15:C26,C58:C69").Areas 'more than 1 selected area
    For Each cell In area 'loop through each cell in the selected range
        If IsEmpty(cell) = False Then
            If IsNumeric(cell) = False Then
                If IsError(Application.Match(cell.Value2,Range("A61:A74"),0)) Then 'search if the name has not being inserted yet
                    Cells(rif_rig + 61,rif_col + 2)) 'Quota Lordo
                    rif_rig = rif_rig + 1
                Else
                    rowNum = Application.WorksheetFunction.Match(cell.Value2,0)
                    Cells(rowNum,rif_col + 11) = (Cells(rowNum,rif_col + 2)) 'Quota Lordo
                    If Cells(rowNum,rif_col + 1).Value2 Then
                        Cells(rowNum,rif_col + 7) = Cells(rowNum,rif_col + 1).Value2 'Ruolo
                    Else
                        Cells(rowNum,rif_col + 1).Value2 'Ruolo
                    End If
                End If
            Else
            End If
        Else
        End If
    Next
areaCount = areaCount + 1
Next

谢谢, 卡洛塔。

P.S。我是VBA的新手,所以我的代码可能很混乱

解决方法

您可以尝试修改此代码

Sub test()
    
    Dim Sh1 As Worksheet,Sh2 As Worksheet
    Dim CollNames As Collection
    Dim Cella As Range
    Dim R As Long
    
    Set Sh1 = ThisWorkbook.Sheets("Foglio1") 'origine
    Set Sh2 = ThisWorkbook.Sheets("Foglio2") 'destinazione
    Set CollNames = New Collection
    With Sh1
        R = 1
        On Error Resume Next
        For Each Cella In .Range("A1:A" & .Cells(Rows.Count,1).End(xlUp).Row) 
            CollNames.Add Sh2.Cells(R,1),CStr(Cella)
            If Err.Number = 0 Then
                CollNames(Cella) = Cella
                R = R + 1
            Else
                Err.Clear
            End If
            CollNames(Cella).Offset(0,1) = CollNames(Cella).Offset(0,1) + Cella.Offset(0,1)
        Next Cella
        On Error GoTo 0
    End With
    Set Sh1 = Nothing
    Set Sh2 = Nothing
    Set CollNames = Nothing
    
End Sub

代码读取Sh1的A和B列中的数据,并在Sh2的相同列中报告结果。

您需要修改For Each语句中的范围和偏移量。

,

您不必遍历范围内的所有区域(大约For Each area In Worksheets("XXX")...)。只需在范围内的单元格上循环,范围对象将负责将它们全部显示给您。

此外,不要将所有范围都写入宏。您每次必须更改代码以选择其他单元格。在运行宏并使用Selection对象之前,选择所需的单元格更加容易(请不要担心这里的文本太多-实际上,少于30行的代码,其余所有都是给您的注释):

Sub SumsByNames()
Dim rSource As Range
Dim aCell As Range  ' Iterate by each cells in current Selection
Dim aData As Variant    ' Array for Names and ranges with this Name
Dim i As Long
    aData = Array() ' Empty array
    Set rSource = Application.Intersect(Selection,ActiveSheet.UsedRange)
    For Each aCell In rSource ' If cell is not empty then .text also not empty string
        If aCell.Text <> vbNullString Then
            If Not IsNumeric(aCell) Then
                Call addToData(aData,aCell.Text,aCell.Offset(0,1))
            End If
        End If
    Next aCell
    Set aCell = Worksheets("Result").Range("A61")
    aCell.CurrentRegion.ClearContents
    For i = LBound(aData) To UBound(aData)
        aCell.Value = aData(i)(0)   ' Paste Name
        aCell.Offset(0,1).Value = Application.WorksheetFunction.Sum(aData(i)(1))
        Set aCell = aCell.Offset(1,0)
    Next i
End Sub

Sub addToData(ByRef aData As Variant,sName As String,rCell As Range)
Dim i As Long
    For i = LBound(aData) To UBound(aData)
        If aData(i)(0) = sName Then
            Set aData(i)(1) = Application.Union(aData(i)(1),rCell)
            Exit Sub
        End If
    Next i
    i = UBound(aData) + 1
    ReDim Preserve aData(i)
    aData(i) = Array(sName,rCell)
End Sub

示例文件mySumIf_TestDemo.xlsm

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-