我要遍历特定目录中的25个工作簿,并且需要在每个工作簿中隐藏相同的列。
我已经设置了代码,以使其遍历每个工作簿,但是在隐藏列方面却失败了。我已经完成了谷歌搜索,但是缺少了一些东西。
无效的特定代码:
Worksheets("Ops1").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
Worksheets("Ops2").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
整个过程:
Dim xFd As FileDialog
Dim xFdItem As Variant
Dim xFileName As String
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
If xFd.Show = -1 Then
xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
xFileName = Dir(xFdItem & "*.xls*")
Do While xFileName <> ""
With Workbooks.Open(xFdItem & xFileName)
'your code here
Worksheets("Ops1").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
Worksheets("Ops2").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
End With
xFileName = Dir
Loop
End If
我收到超出范围的运行时错误代码'9'下标。
答案 0 :(得分:0)
可以简化一些,但这应该可以解决问题。只需重用您的代码即可:
Dim xFd As FileDialog
Dim xFdItem As Variant
Dim xFileName As String
Dim X As Long, C As Long, lCol As Long
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
If xFd.Show = -1 Then
xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
xFileName = Dir(xFdItem & ".xls")
Do While xFileName <> ""
With Workbooks.Open(xFdItem & xFileName)
'not sure if all your sheets are called OpsX, might need to change this
For X = 1 To 2 'Loop through all the sheets
With .Worksheets("Ops" & X) 'Note the use of <[ . ]> (DOT) in the With statement
lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column 'Get the last column, relative to row 1
For C = lCol To 1 Step -1 'Loop through all columns, starting at last one
Select Case C
Case 5 To 31 'F:AE
.Cells(1, C).EntireColumn.Hidden = True
Case 33 To 43 'AG:AQ
.Cells(1, C).EntireColumn.Hidden = True
Case 45 To 94 'AS:CP
.Cells(1, C).EntireColumn.Hidden = True
Case 101 To 136 'CW:EF
.Cells(1, C).EntireColumn.Hidden = True
End Select
Next C
End With
Next X
End With
xFileName = Dir
Loop
End If
答案 1 :(得分:0)
您可以尝试将范围设置为这样的变量。
Dim xFd As FileDialog
Dim xFdItem As Variant
Dim xFileName As String
Dim sht1ColumnsToHide As Range
Dim sht2ColumnsToHide As Range
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set ws1 = Worksheet("Ops1")
Set ws2 = Worksheet("Ops2")
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
If xFd.Show = -1 Then
xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
xFileName = Dir(xFdItem & "*.xls*")
Do While xFileName <> ""
With Workbooks.Open(xFdItem & xFileName)
'your code here
Set ws1 = Worksheets("Ops1")
Set ws2 = Worksheets("Ops2")
With ws1
Set sht1ColumnsToHide = Application.Union(.Columns("F:AE"), _
.Columns("AG:AQ"), _
.Columns("AS:CP"), _
.Columns("CW:EF"))
sht1ColumnsToHide.EntireColumn.Hidden = True
End With
With ws2
Set sht2ColumnsToHide = Application.Union(.Columns("F:AE"), _
.Columns("AG:AQ"), _
.Columns("AS:CP"), _
.Columns("CW:EF"))
sht2ColumnsToHide.EntireColumn.Hidden = True
End With
End With
xFileName = Dir
Loop
End If