周一至周五 : 08:30 - 17:30 客服专员电话/微信:18049989370 QQ:857188287
微信咨询

扫码微信咨询

关注公众号

关注微信公众号

电话: 021 5161 9370
返回顶部
VBA根据Shee1中某列关键词把结果复制到Sheet2中进行交叉互算
显示全部楼层 倒序浏览 发表日期 2026-06-11 11:36:35 22次阅读 0次回复

关键词复制列VBA.rar

2.84 KB, 下载次数: 0

本帖最后由 hong90342 于 2026-6-11 12:05 编辑

VBA根据Sheet1中某列关键词把结果复制到Sheet2中进行交叉运算
使用场景:excel中嵌套自动计算,sheet1从sheet2中取数,然后把结果返回sheet2再进行二次计算。
  1. Imports SpreadsheetGear
  2. Imports C1.Silverlight
  3. Imports C1.Silverlight.C1MessageBoxButton
  4. Imports C1.Silverlight.C1MessageBoxIcon
  5. Imports Newtonsoft.Json
  6. Imports Newtonsoft.Json.Linq
  7. Imports Microsoft.VisualBasic
  8. Imports System.IO
  9. Imports System.Text
  10. Imports System.Net
  11. Imports System.Windows.forms
  12. Imports System.Collections.Generic

  13. Namespace ExcelViewVBDotnet
  14.     Public Class StandardInterface
  15.         '预留位置1
  16.         '预留位置2
  17.         Dim EV As SpreadsheetGear.Windows.Controls.WorkbookView
  18.         Dim AW As SpreadsheetGear.IWorkbook
  19.         Dim Range As SpreadsheetGear.IRange

  20.         '==================== 可配置区域,按需修改即可,无需动核心逻辑 ====================
  21.         Private Const SourceSheetName As String = "Sheet1"
  22.         Private Const TargetSheetName As String = "Sheet2"
  23.         Private Const KeywordColumn As Integer = 12 ' 取数来源列,按您的要求固定为12
  24.         Private Const MatchKeyColumn As Integer = 1 ' A列:项目匹配列
  25.         Private Const CopyStartColumn As Integer = 33 ' AH列:复制起始列
  26.         Private Const CopyEndColumn As Integer = 45 ' AT列:复制结束列
  27.         Private Const MatchKeyword As String = "自动取数计算" ' 匹配关键词
  28.         Private Const SourceHeaderRow As Integer = 7 ' Sheet1表头行号
  29.         Private Const TargetHeaderRow As Integer = 2 ' Sheet2表头行号
  30.         ' 关闭所有调试弹窗,运行流畅无卡顿
  31.         Private Const EnableDebugPopup As Boolean = False
  32.         Private Const ShowColumnDebug As Boolean = False
  33.         '====================================================================================

  34.         Public Sub Workbook_Open(OldRoot As Object, NewRoot As Object, Excel As SpreadsheetGear.Windows.Controls.WorkbookView)
  35.             EV = Excel
  36.             Excel.GetLock()
  37.             AW = Excel.ActiveWorkbook
  38.             Range = AW.ActiveWorksheet.Range
  39.             Excel.ReleaseLock()
  40.         End Sub

  41.         Public Sub RangeSelection(sender As Object, e As SpreadsheetGear.Windows.Controls.RangeSelectionChangedEventArgs)
  42.         End Sub

  43.         Public Sub RangeChanged(sender As Object, e As SpreadsheetGear.Windows.Controls.RangeChangedEventArgs)
  44.         End Sub

  45.         Public Sub ButtunClick(sender As Object, e As SpreadsheetGear.Windows.Controls.ShapeActionEventArgs)
  46.             AW.WorkbookSet.GetLock()
  47.             Dim buttonName As String = e.Shape.Name
  48.             AW.WorkbookSet.ReleaseLock()

  49.             If buttonName = "Button 22" Then
  50.                 Try
  51.                     CopyDataByCondition()
  52.                 Catch ex As Exception
  53.                     C1MessageBox.Show(ex.Message, "操作失败", C1MessageBoxButton.OK, C1MessageBoxIcon.Error)
  54.                 End Try
  55.             End If
  56.         End Sub

  57.         Public Sub FollowHyperlink(sender As Object)
  58.         End Sub

  59.         ''' <summary>
  60.         ''' 核心业务逻辑:按条件匹配更新AH-AS列范围,修复API调用错误
  61.         ''' </summary>
  62.         Private Sub CopyDataByCondition()
  63.             Try
  64.                 AW.WorkbookSet.GetLock()
  65.                                 AW.WorkbookSet.Calculation = Calculation.Manual
  66.                 ' 工作簿与工作表校验
  67.                 If AW Is Nothing Then
  68.                     Throw New Exception("错误:工作簿未加载")
  69.                 End If
  70.                 Dim wsSource As IWorksheet = AW.Worksheets(SourceSheetName)
  71.                 Dim wsTarget As IWorksheet = AW.Worksheets(TargetSheetName)
  72.                 If wsSource Is Nothing Then Throw New Exception("错误:Sheet1 不存在")
  73.                 If wsTarget Is Nothing Then Throw New Exception("错误:Sheet2 不存在")

  74.                 ' 列范围合法性校验
  75.                 If CopyStartColumn > CopyEndColumn Then
  76.                     Throw New Exception("配置错误:复制起始列(" & CopyStartColumn & ") > 复制结束列(" & CopyEndColumn & ")")
  77.                 End If
  78.                 ' 【89行核心修复:SpreadsheetGear中IWorksheet无ColumnCount属性,需通过Cells属性获取】
  79.                 Dim maxSheetColumn As Integer = wsSource.Cells.ColumnCount
  80.                 If CopyEndColumn > maxSheetColumn Then
  81.                     Throw New Exception("配置错误:复制结束列(" & CopyEndColumn & ") > 表格最大列数(" & maxSheetColumn & ")")
  82.                 End If

  83.                 ' 1. 预加载目标表匹配字典
  84.                 Dim targetMatchDict As Dictionary(Of String, Integer)
  85.                 targetMatchDict = New Dictionary(Of String, Integer)()
  86.                 Dim targetDataStartRow As Integer = TargetHeaderRow + 1
  87.                 Dim targetUsedRng As IRange = wsTarget.UsedRange
  88.                 Dim targetUsedRngStartRow As Integer = targetUsedRng.Row
  89.                 Dim targetUsedRngRowCount As Integer = targetUsedRng.RowCount
  90.                 Dim targetLastRow As Integer = targetUsedRngStartRow + targetUsedRngRowCount - 1

  91.                 ' 遍历目标表,填充匹配字典
  92.                 For targetRow As Integer = targetDataStartRow To targetLastRow
  93.                     Dim targetKeyValue As Object = wsTarget.Cells(targetRow, MatchKeyColumn).Value
  94.                     If targetKeyValue IsNot Nothing AndAlso Not String.IsNullOrEmpty(targetKeyValue.ToString()) Then
  95.                         Dim keyStr As String = targetKeyValue.ToString().Trim()
  96.                         If Not targetMatchDict.ContainsKey(keyStr) Then
  97.                             targetMatchDict.Add(keyStr, targetRow)
  98.                         End If
  99.                     End If
  100.                 Next

  101.                 If targetMatchDict.Count = 0 Then
  102.                     Throw New Exception("提示:Sheet2中无有效项目数据,无法匹配")
  103.                 End If

  104.                 ' 2. 遍历源表,按条件匹配更新
  105.                 Dim sourceDataStartRow As Integer = SourceHeaderRow + 1
  106.                 Dim sourceUsedRng As IRange = wsSource.UsedRange
  107.                 Dim sourceUsedRngStartRow As Integer = sourceUsedRng.Row
  108.                 Dim sourceUsedRngRowCount As Integer = sourceUsedRng.RowCount
  109.                 Dim sourceLastRow As Integer = sourceUsedRngStartRow + sourceUsedRngRowCount - 1

  110.                 If sourceLastRow < sourceDataStartRow Then
  111.                     Throw New Exception("提示:Sheet1中无有效数据行,起始行:" & sourceDataStartRow & ",最后行:" & sourceLastRow)
  112.                 End If

  113.                 ' 统计信息
  114.                 Dim updateSuccessRowCount As Integer = 0
  115.                 Dim matchKeywordCount As Integer = 0
  116.                 Dim noMatchCount As Integer = 0
  117.                 Dim targetColumnEmptyCount As Integer = 0

  118.                 ' 遍历源表数据行
  119.                 For sourceRow As Integer = sourceDataStartRow To sourceLastRow
  120.                     ' 读取取数来源列内容
  121.                     Dim keywordCellValue As Object = wsSource.Cells(sourceRow, KeywordColumn).Value
  122.                     If keywordCellValue Is Nothing OrElse String.IsNullOrEmpty(keywordCellValue.ToString().Trim()) Then
  123.                         targetColumnEmptyCount += 1
  124.                         Continue For
  125.                     End If

  126.                     ' 关键词清洗与匹配
  127.                     Dim rawContent As String = keywordCellValue.ToString()
  128.                     Dim cleanContent As String = rawContent.Trim().Replace(vbCrLf, "").Replace(vbTab, "").Replace(" ", "")
  129.                     Dim cleanKeyword As String = MatchKeyword.Trim().Replace(" ", "")
  130.                     Dim isKeywordMatch As Boolean = InStr(1, cleanContent, cleanKeyword, CompareMethod.Text) > 0

  131.                     If Not isKeywordMatch Then
  132.                         Continue For
  133.                     End If

  134.                     ' 统计匹配到关键词的行数
  135.                     matchKeywordCount += 1

  136.                     ' 获取A列项目匹配值
  137.                     Dim sourceKeyValue As Object = wsSource.Cells(sourceRow, MatchKeyColumn).Value
  138.                     If sourceKeyValue Is Nothing Then
  139.                         noMatchCount += 1
  140.                         Continue For
  141.                     End If
  142.                     Dim sourceKeyStr As String = sourceKeyValue.ToString().Trim()
  143.                     If String.IsNullOrEmpty(sourceKeyStr) Then
  144.                         noMatchCount += 1
  145.                         Continue For
  146.                     End If

  147.                     ' 字典匹配目标行号
  148.                     If Not targetMatchDict.ContainsKey(sourceKeyStr) Then
  149.                         noMatchCount += 1
  150.                         Continue For
  151.                     End If
  152.                     Dim targetRow As Integer = targetMatchDict(sourceKeyStr)

  153.                     ' 批量复制AH-AS列范围的数值与格式
  154.                     Try
  155.                         ' 遍历AH到AS的每一列,完成复制
  156.                         For currentCol As Integer = CopyStartColumn To CopyEndColumn
  157.                             Dim sourceCellValue As Object = wsSource.Cells(sourceRow, currentCol).Value
  158.                             Dim sourceCellNumberFormat As String = wsSource.Cells(sourceRow, currentCol).NumberFormat
  159.                             wsTarget.Cells(targetRow, currentCol).Value = sourceCellValue
  160.                             wsTarget.Cells(targetRow, currentCol).NumberFormat = sourceCellNumberFormat
  161.                         Next
  162.                         ' 统计成功更新的行数
  163.                         updateSuccessRowCount += 1
  164.                     Catch ex As Exception
  165.                         Throw New Exception("更新失败:源行" & sourceRow & " → 目标行" & targetRow & ",列范围" & CopyStartColumn & "-" & CopyEndColumn & ",错误:" & ex.Message)
  166.                     End Try
  167.                 Next

复制代码

QQ2627049059
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则  允许回帖邮件提醒楼主

快表软件是国内较早研究表格类软件开发平台的团队之一,迄今已有十多年的行业经验.致力于为企事业单位提供实用可靠的数字化平台。
  • 微信公众号

  • 微信小商店

  • 微信客服

  • Powered by Discuz! X3.4 | Copyright © 2022-2024, XiRong Soft. | 快表软件
  • 沪ICP备13033196号 | 营业执照 |上海西戎软件科技有限公司|沪公网安备31011502002146号|沪ICP备13033196号 |