前言
一、错误描述
将excel所有工作表,汇总到一个工作表中:
在thisworkbook中运行如下:
sub 合并所有工作表_在所有行标注工作表名字_无视空行空列_考虑到不规范的多一点的行和列() dim row_num as long, column_num as long, row_num_temp as long, column_num_temp as long, row_num_merge as long, column_num_merge as long, i as long, arr() as long worksheets.add.name = "合并表" sheets("合并表").move before:=sheets(1) for i = 2 to worksheets.count worksheets(i).activate 'usedrange.row,代表使用的第一个行数,在有空行的时候体现,同理,usedrange.column,代表使用的第一个列数,在有空列的时候体现 '那么使用第一行 + 已使用的行数,这样可以规避顶部/左侧有空行,导致获取已使用行号的数据不符合预期(老赵,如果你看到这里不懂,就自己拆开代码,加上空行空列体会一下) row_num = worksheets(i).usedrange.row + worksheets(i).usedrange.rows.count - 1 column_num = worksheets(i).usedrange.column + worksheets(i).usedrange.columns.count - 1 '如果格式很不规范,那么获取的usedrange.rows.count就可能是整个表格的行数,所以要规避这种情况,如果相同,就让他减1 if row_num = worksheets(i).rows.count then row_num = row_num - 1 if column_num = worksheets(i).columns.count then column_num = column_num - 1 '相当于遍历所有的列,都按ctrl + ↑,取数组的最大值 redim arr(1 to column_num) for j = lbound(arr) to ubound(arr) row_num_temp = worksheets(i).cells(row_num + 1, j).end(xlup).row arr(j) = row_num_temp next debug.print (application.worksheetfunction.max(arr)) row_num_temp = application.worksheetfunction.max(arr) '赋予最大值,确定最大的有数据的行数 '相当于遍历所有的行,都按ctrl + ←,取数组的最大值 'erase arr 清空数组,但是也可以不用,直接用redim也可以,如果要保留数组内容,需要加一个preserve redim arr(1 to row_num_temp) for j = lbound(arr) to ubound(arr) column_num_temp = worksheets(i).cells(j, column_num + 1).end(xltoleft).column arr(j) = column_num_temp next debug.print (application.worksheetfunction.max(arr)) column_num_temp = application.worksheetfunction.max(arr) '赋予最大值,确定最大的有数据的列数 worksheets(i).range(cells(1, 1), cells(row_num_temp, column_num_temp)).select selection.copy sheets("合并表").cells(row_num_merge + 1, 2) worksheets("合并表").cells(row_num_merge + 1, 1) = worksheets(i).name row_num_merge = sheets("合并表").usedrange.rows.count next '将首行标题转为所有行(选择空值,=上面的数据) worksheets("合并表").activate columns("a:a").select selection.specialcells(xlcelltypeblanks).select application.cutcopymode = false selection.formular1c1 = "=r[-1]c" columns("a:a").select selection.copy selection.pastespecial paste:=xlpastevalues, operation:=xlnone, skipblanks:=false, transpose:=false application.cutcopymode = false range("a1").select end sub
新建模块,运行如下:
二、原因调查
发现是工作表中数据存在异常,例如:
最下面存在个别数据,导致复制粘贴的时候单元格数量不足,形成此错误;
总结
分享:
“难道生命这漫长进程中所有的努力和希望,都是为了那飞娥扑火的一瞬间?”“飞蛾并不觉得阴暗,它至少享受了短暂的光明。"
到此这篇关于关于vba代码运行时错误1004 应用程序定义或对象定义错误问题的文章就介绍到这了,更多相关vba运行时错误1004内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论