VBA如何在新建的workbook中增加sheet
首先,我打开一个空白的workbook,运行下面的代码,目的是批量处理一个文件夹的workbook运行到“Sheets.Addafter:=Sheets(2)”时,增加的...
首先,我打开一个空白的workbook,运行下面的代码,目的是批量处理一个文件夹的workbook
运行到“Sheets.Add after:=Sheets(2)”时,增加的sheet是在空白的workbook中而不是我要处理的workbook。我在office2010中运行。
Sub dealfiles()
' 操作入口
Dim sFolder As String
Dim targetFolder As String
Dim fileName As String
Dim newFile As String
Dim i As Integer
Dim fileCount As Integer
Application.DisplayAlerts = False
i = 1
fileCount = 1
'sFolder为输入文件夹
sFolder = "C:\Users\flfy\Desktop\test\"
'targetFolder为输出文件夹
targetFolder = "D:\temp\"
xlsname = Dir(sFolder & "*.xlsx")
Do
If xlsname = "" Then
Exit Do
End If
fileName = sFolder & xlsname
Debug.Print "读取文件:" & fileName
newFile = targetFolder + "file" + Str(fileCount) + ".xls"
Debug.Print "写入:" & newFile
Call deal(fileName, xlsname, newFile)
xlsname = Dir()
fileCount = fileCount + 1
Loop
Debug.Print "OK"
End Sub
Sub deal(fileName As String, ByVal xlsname, newFile As String)
'
Dim s1 As Excel.Worksheet
Dim s2 As Excel.Worksheet
Dim s3 As Excel.Worksheet
Workbooks.Open fileName:=fileName
Workbooks(xlsname).Activate
'在第二个之后创建新表
Sheets.Add after:=Sheets(Sheets.Count)
应该是运行到“Sheets.Add after:=Sheets(Sheets.Count)”时,增加的sheet是在空白的workbook中而不是我要处理的workbook。 展开
运行到“Sheets.Add after:=Sheets(2)”时,增加的sheet是在空白的workbook中而不是我要处理的workbook。我在office2010中运行。
Sub dealfiles()
' 操作入口
Dim sFolder As String
Dim targetFolder As String
Dim fileName As String
Dim newFile As String
Dim i As Integer
Dim fileCount As Integer
Application.DisplayAlerts = False
i = 1
fileCount = 1
'sFolder为输入文件夹
sFolder = "C:\Users\flfy\Desktop\test\"
'targetFolder为输出文件夹
targetFolder = "D:\temp\"
xlsname = Dir(sFolder & "*.xlsx")
Do
If xlsname = "" Then
Exit Do
End If
fileName = sFolder & xlsname
Debug.Print "读取文件:" & fileName
newFile = targetFolder + "file" + Str(fileCount) + ".xls"
Debug.Print "写入:" & newFile
Call deal(fileName, xlsname, newFile)
xlsname = Dir()
fileCount = fileCount + 1
Loop
Debug.Print "OK"
End Sub
Sub deal(fileName As String, ByVal xlsname, newFile As String)
'
Dim s1 As Excel.Worksheet
Dim s2 As Excel.Worksheet
Dim s3 As Excel.Worksheet
Workbooks.Open fileName:=fileName
Workbooks(xlsname).Activate
'在第二个之后创建新表
Sheets.Add after:=Sheets(Sheets.Count)
应该是运行到“Sheets.Add after:=Sheets(Sheets.Count)”时,增加的sheet是在空白的workbook中而不是我要处理的workbook。 展开
2个回答
推荐于2016-07-28 · 知道合伙人软件行家
关注
展开全部
试试把它改为:Workbooks(xlsname).Sheets.Add after:=Workbooks(xlsname).Sheets(Workbooks(xlsname).Sheets.Count)
更多追问追答
追问
可以了,但是我继续运行的时候为什么会下标越界?
Sheets("Results").Select
我明明有一个sheet的名字叫做Results,我改成sheet(2).Select也不行
追答
那就把它改成:Workbooks(xlsname).Sheets("Results").Select
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |