想在VB加入一个按钮执行表格汇总程序,加入按钮后不知道如何编写代码调用程序执行,请帮忙修改一下,谢谢!

zyqballack2008 2025-04-03 23:51:56

VB中想增加一个按钮来执行以下程序,执行报错无法调用,请帮忙修改一下程序,感谢!

 

 

 

 

 

 

Private Sub CommandButton1_Click()
MergeSheetsFullData

End Sub

 Sub MergeSheetsFullData()
    Dim ws As Worksheet
    Dim target As Worksheet
    Dim sourceLastRow As Long, sourceLastCol As Integer
    Dim targetLastRow As Long
    
    ' 设置目标为"汇总"Sheet(需提前创建)
    Set target = ThisWorkbook.Sheets("汇总")
    Application.ScreenUpdating = False
    
    ' 清除旧数据(保留标题行)
    If target.UsedRange.Rows.Count > 1 Then
        target.Range("A2", target.Cells.SpecialCells(xlCellTypeLastCell)).ClearContents
    End If
    
    ' 遍历所有Sheet
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> target.Name Then
            ' 动态获取源数据范围
            sourceLastRow = GetLastRow(ws)  ' 获取实际最后一行
            sourceLastCol = GetLastColumn(ws) ' 获取实际最后一列
            
            If sourceLastRow > 1 And sourceLastCol > 0 Then
                ' 构建动态数据范围(A2到最后一列最后一行的矩形区域)
                With ws.Range(ws.Cells(2, 1), ws.Cells(sourceLastRow, sourceLastCol))
                    ' 获取目标粘贴起始位置
                    targetLastRow = target.Cells(target.Rows.Count, 1).End(xlUp).Row + 1
                    If targetLastRow = 2 And target.Range("A1").Value = "" Then targetLastRow = 1
                    
                    ' 精准复制(值+格式)
                   .Copy
target.Cells(targetLastRow, 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
                End With
            End If
        End If
    Next ws
    
    Application.ScreenUpdating = True
    MsgBox "合并完成!共处理 " & ThisWorkbook.Sheets.Count - 1 & " 个Sheet", vbInformation
End Sub


' 获取实际最后一行(考虑所有列)
Function GetLastRow(ws As Worksheet) As Long
    On Error Resume Next
    GetLastRow = ws.Cells.Find("*", , xlFormulas, , xlByRows, xlPrevious).Row
    If Err.Number <> 0 Then GetLastRow = 1
    On Error GoTo 0
End Function

' 获取实际最后一列(考虑所有行)
Function GetLastColumn(ws As Worksheet) As Integer
    On Error Resume Next
    GetLastColumn = ws.Cells.Find("*", , xlFormulas, , xlByColumns, xlPrevious).Column
    If Err.Number <> 0 Then GetLastColumn = 1
    On Error GoTo 0
End Function
End Function


End Sub

 

...全文
78 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 实力派 技术很长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长测试长度长长长长长长长长长 04-07
  • 打赏
  • 举报
回复

注释掉所有On Error Resume Next语句,在VB IDE中运行,
出错后点击调试,光标会停在出错的那条语句处,
或者
事先在怀疑可能有逻辑错误的语句处设置断点,运行经过断点时中断,

此时可以在立即窗口中使用
?变量名

?函数名(函数参数)

过程名(参数)
辅助调试。

16,722

社区成员

发帖
与我相关
我的任务
社区描述
VB技术相关讨论,主要为经典vb,即VB6.0
社区管理员
  • VB.NET
  • 水哥阿乐
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧