当前位置: 移动技术网 > IT编程>脚本编程>VBScript > VBS实现工作表按指定表头自动分表

VBS实现工作表按指定表头自动分表

2017年12月08日  | 移动技术网IT编程  | 我要评论

羔羊绝艳传说,侧耳倾听下载,谷正涵

在我们实际工作中经常遇到将工作表按某一表头字段分开的情况,我们一般的做法是先按指定表头排序然后分段复制粘贴出去,不但麻烦还很容易搞错。

下面的vbs脚本就是实现的工作表按指定表头(由用户选择)自动分表功能。需要的朋友只要将要操作的工作表拖放到脚本文件上即可轻松实现工作表分表(暂时只适用于xp系统):

复制代码 代码如下:

'拖动工作表至vbs脚本实现按指定表头自动分表
on error resume next
if wscript.arguments(0) = "" then wscript.quit
dim objexcel, excelfile, maxrows, maxcolumns, shcount
excelfile = wscript.arguments(0)
if lcase(right(excelfile,4)) <> ".xls" and lcase(right(excelfile,4)) <> ".xls" then wscript.quit
set objexcel = createobject("excel.application")
objexcel.visible = false
objexcel.workbooks.open excelfile
'获取工作表初始sheet总数
shcount = objexcel.sheets.count
'获取工作表有效行列数
maxrows = objexcel.activesheet.usedrange.rows.count
maxcolumns = objexcel.activesheet.usedrange.columns.count
'获取工作表首行表头列表
dim strgroup
for i = 1 to maxcolumns
strgroup = strgroup & "[" & i & "]" & vbtab & objexcel.cells(1, i).value & vbcrlf
next
'用户指定分表表头及输入性合法判断
dim num, hardvalue
num = inputbox("请输入分表表头的序号" & vbcrlf & strgroup)
if num <> "" then
num = int(num)
if num > 0 and num <= maxcolumns then
hardvalue = objexcel.cells(1, num).value
else
objexcel.quit
set objexcel = nothing
wscript.quit
end if
else
objexcel.quit
set objexcel = nothing
wscript.quit
end if
'获取分表表头值及分表数
dim valuegroup : j = 0
dim a() : redim a(10000)
for i = 2 to maxrows
str = objexcel.cells(i, num).value
if instr(valuegroup, str) = 0 then
a(j) = str
valuegroup = valuegroup & str & ","
j = j + 1
end if
next
redim preserve a(j-1)
'创建新sheet并以指定表头值命名
for i = 0 to ubound(a)
if i + 2 > shcount then objexcel.sheets.add ,objexcel.sheets("sheet" & i + 1),1,-4167
next
for i = 0 to ubound(a)
objexcel.sheets("sheet" & i + 2).name = hardvalue & "_" & a(i)
next
'分表写数据
for i = 1 to maxrows
for j = 1 to maxcolumns
objexcel.sheets(1).select
str = objexcel.cells(i,j).value
if i = 1 then
for k = 0 to ubound(a)
objexcel.sheets(hardvalue & "_" & a(k)).select
objexcel.cells(i,j).value = str
objexcel.cells(1, maxcolumns + 1).value = 1
next
else
objexcel.sheets(hardvalue & "_" & objexcel.cells(i,num).value).select
if j = 1 then x = objexcel.cells(1, maxcolumns + 1).value + 1
objexcel.cells(x ,j).value = str
if j = maxcolumns then objexcel.cells(1, maxcolumns + 1).value = x
end if
next
next
for i = 0 to ubound(a)
objexcel.sheets(hardvalue & "_" & a(i)).select
objexcel.cells(1, maxcolumns + 1).value = ""
next
objexcel.activeworkbook.save
objexcel.quit
set objexcel = nothing
wscript.echo "提示:对" & excelfile & "的分表操作完成"

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网