You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA横向排序宏仅在特定工作表生效问题求助

问题:Excel VBA横向排序宏跨工作表/工作簿失效排查

需求与问题背景

  • 编写VBA宏实现每行数字横向升序排序,直至遇到空单元格或非数值数据(Excel无原生该功能)
  • 数据规模:73行7列,所有数值不超过50
  • 核心问题:宏仅在名为Sheet1的工作表中正常生效,更换工作表引用为其他表名、改用ActiveSheet或新建工作簿后,宏均无法正常运行

已尝试的排查操作

  • 修改代码中固定工作表引用为目标表名称
  • 将Worksheets("Sheet1")替换为ActiveSheet以适配当前活动表
  • 添加计数器模块确认脚本是否执行及循环次数
  • 调整目标单元格格式为常规、数值、自定义等多种类型

待排查代码

代码1:SortAndMove

Sub SortAndMove()
    Dim rng As Range
    
    ' Set the initial range to the second row, columns A to F
    Set rng = Worksheets("Sheet1").Range("A1:G1")
    
    ' Loop until the first cell in the current row is not a number or is <= 0
    Do While IsNumeric(rng.Cells(1, 1).Value) And rng.Cells(1, 1).Value > 0
        ' Sort the selected range horizontally in ascending order
        rng.Sort Key1:=rng.Cells(1, 1), Order1:=xlAscending, Header:=xlNo
        
        ' Move the selection down one row
        Set rng = rng.Offset(1, 0).Resize(, 7) ' Resize to select the first six columns

    Loop
End Sub

代码2:HorizontalSort

Sub HorizontalSort()

    Dim rng As Range
    Dim counter As Range
    Dim i As Integer
    
    
    ' Set the initial range to the second row, columns A to G
    Set rng = Worksheets("Sheet1").Range("A1:G1")
    
    ' Sets the range where the counter will be updated on the worksheet
    Set counter = Worksheets("Sheet1").Range("I1")
    i = 0
    
    
    ' Loop until the first cell in the current row is not a number or is <= 0
    Do While IsNumeric(rng.Cells(1, 1).Value) And rng.Cells(1, 1).Value > 0
        ' Sort the selected range horizontally in ascending order
        rng.Sort Key1:=rng.Cells(1, 1), Order1:=xlAscending, Header:=xlNo
        
        ' Move the selection down one row
        Set rng = rng.Offset(1, 0).Resize(, 7) ' Resize to select the first seven columns
        
        ' Increment the counter and print it's value during each iteration of the loop
        i = i + 1
        counter.Value = i
        
    Loop
    
End Sub

请求

排查代码存在的问题,或分析宏在非Sheet1工作表/新工作簿中失效的原因。

内容的提问来源于stack exchange,提问作者NonKonnektion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 14:15:21