【发布时间】:2016-01-11 09:16:34
【问题描述】:
我正在处理大量历史数据,并制作了一个宏来将这些 Excel 电子表格格式化为 Access 友好的信息。但是,将这些 excel 文件导入 Access 时遇到问题。无论我在 VBA 中编码什么,Access 仍然认为在前四个实际数据之后有大约 30 个空白列。防止这种情况的唯一方法是手动进入并删除列。出于某种原因,我的 VBA 代码不会阻止它。我正在处理很多电子表格,因此手动删除这些列需要相当长的时间。我的代码如下;关于如何让 Access 正确解释这些的任何想法?
Public CU_Name As String
Sub RegulatorFormat()
Dim wks As Worksheet
Dim wks2 As Worksheet
Dim iCol As Long
Dim lastRow As Long
Dim Desc As Range
Dim lastCol As Long
Application.ScreenUpdating = False
Worksheets.Select
Cells.Select
Selection.ClearFormats
Call FormulaBeGone
ActiveSheet.Cells.Unmerge
CU_Name = [B1].Value
lastRow = Range("C" & Rows.Count).End(xlUp).Row
Set Desc = Range("A1", "A57")
Desc.Select
For Each wks In ActiveWindow.SelectedSheets
With wks
On Error Resume Next
For iCol = 16 To 4 Step -1
Dim PerCol As Date
PerCol = Cells(1, iCol)
.Columns(iCol).Insert
Range(Cells(1, iCol), Cells(lastRow, iCol)) = CU_Name
.Columns(iCol).Insert
Range(Cells(1, iCol), Cells(lastRow, iCol)) = Desc.Value
.Columns(iCol).Insert
Cells(1, iCol).Value = PerCol
Range(Cells(1, iCol), Cells(lastRow, iCol)) = Cells(1, iCol)
Range(Cells(1, iCol), Cells(lastRow, iCol)).NumberFormat = "mm/dd/yyyy"
Next iCol
End With
Next wks
Rows("1:2").EntireRow.Delete
Columns("A:C").EntireColumn.Delete
lastCol = ws.Cells.Find(What:="*", _
After:=ws.Cells(1, 1), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
For Each wks2 In ActiveWindow.SelectedSheets
With wks2
On Error Resume Next
For iCol = 52 To 6 Step -4
lastRow = Range("C" & Rows.Count).End(xlUp).Row
Set CutRange = Range(Cells(1, iCol), Cells(54, iCol - 3))
CutRange.Select
Selection.Cut
Range("A" & lastRow + 1).Select
ActiveSheet.Paste
Next iCol
End With
Next wks2
Columns("E:ZZ").Select
Selection.EntireColumn.Delete
Application.ScreenUpdating = True
Rows("1").Insert
[A1] = "Period"
[B1] = "Line#"
[C1] = "CU_Name"
[D1] = "Balance"
Columns("E:BM").Select
Selection.Delete Shift:=xlToLeft
Call Save
End Sub
Sub FormulaBeGone()
Worksheets.Select
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues
ActiveSheet.Select
Application.CutCopyMode = False
End Sub
Sub Save()
Dim newFile As String
newFile = CU_Name
ChDir ("W:\ALM\Statistics\MO Automation\2015")
'Save folder
ActiveWorkbook.SaveAs Filename:=newFile
'Later should seperate CU's into folder by province and year
End Sub
【问题讨论】:
-
不清楚:您的工作簿中有多少工作表?你做了很多操作
For Each wks In ActiveWindow.SelectedSheets,但 Columns.Delete 只在一张纸上(可能是最后一张)。 --- 另外,您使用.Select的方式太频繁了。尝试直接使用范围,如果只是为了提高代码的可读性。 -
您可以像查找最后一行一样查找最后一列。只需使用列
-
可以有其他工作表,但不是必须的。我希望每次都拉入第一个工作表,因此 column.delete 仅在第一个工作表上使用。这些部分有效,问题是它认为大约有 30 个额外的列没有数据。在未能实现具有范围的解决方案后使用了很多 .selects(从“记录宏”复制。