【发布时间】:2015-07-10 20:18:12
【问题描述】:
我是 Excel vba 的新手,但我已经使用 access vba 有一段时间了。
我有一些代码可以根据 excel 中的不同列将主文件拆分为其他几个文件
Sub SplitbyValue()
Dim FromR As Range, ToR As Range, All As Range, Header As Range
Dim Wb As Workbook
Dim Ws As Worksheet
'Get the header in this sheet
Set Header = Range("D8").EntireRow
'Visit each used cell in column D, except the header
Set FromR = Range("D9")
For Each ToR In Range(FromR, Range("D" & Rows.Count).End(xlUp).Offset(1))
'Did the value change?
If FromR <> ToR Then
'Yes, get the cells between
Set All = Range(FromR, ToR.Offset(-1)).EntireRow
'Make a new file
Set Wb = Workbooks.Add(xlWBATWorksheet)
'Copy the data into there
With Wb.ActiveSheet
Header.Copy .Range("A8")
All.Copy .Range("A9")
End With
'Save it
Wb.SaveAs ThisWorkbook.Path & "\" & Format(Date, "yyyy.mm.dd") & _
" - " & FromR.Value & ".xls", xlWorkbookNormal
Wb.Close
'Remember the start of this section
Set FromR = ToR
End If
Next
End Sub
这对主工作表很有用,但必须复制多个选项卡,而且这只捕获一张工作表。如何扩展它以便将其他工作表也复制到该文件中?
示例: A栏 编号1 ID2 ID3
这会创建三个文件 (Id1)(Id2)(Id3) 但忽略其他工作表。
【问题讨论】:
-
你需要一个
For Each (sheet variable) in (Workbook variable).Sheets循环来围绕你的整个事情。现在它只在您启动宏时执行激活的工作表。