编写一个使用文件系统对象循环遍历电子表格所在目录的宏。循环遍历每个工作表并分析列名。
以下是您将如何循环浏览每张纸。
Private Sub CommandButton7_Click()
Dim ws As Excel.Worksheet
Dim iCol As Integer
Dim strName As String
Dim iIndex As Integer
'Loop through the sheets.
For iIndex = 1 To Application.Worksheets.Count
Set ws = Application.Worksheets(iIndex)
'Loop through the columns.
For iCol = 1 To ws.UsedRange.Columns.Count
'Check row 1 of this column for first char of *
If Left(ws.Cells(1, iCol).Value, 1) = "*" Then
'We have found a column with the first char of *
ws.Columns(iCol).EntireColumn.Delete
End If
Next iCol
Next iIndex
ActiveWorkbook.SaveAs Filename:="C:\temp\newfiles\" & ActiveWorkbook.Name, FileFormat:=xlWorkbookNormal
End Sub
如果您想在单元格中的任何位置查找 *,您可以使用 instr()
Private Sub CommandButton7_Click()
Dim ws As Excel.Worksheet
Dim iCol As Integer
Dim strName As String
Dim iIndex As Integer
'Loop through the sheets.
For iIndex = 1 To Application.Worksheets.Count
Set ws = Application.Worksheets(iIndex)
'Loop through the columns.
For iCol = 1 To ws.UsedRange.Columns.Count
'Check row 1 of this column for the char of *
If instr(ws.Cells(1, iCol).Value, "*") > 0 Then
'We have found a column with the char of *
ws.Columns(iCol).EntireColumn.Delete
End If
Next iCol
Next iIndex
ActiveWorkbook.SaveAs Filename:="C:\temp\newfiles\" & ActiveWorkbook.Name, FileFormat:=xlWorkbookNormal
End Sub
这是给定目录中的基本循环文件。希望这能让你到达那里。
Private Sub CommandButton7_Click()
Dim wb As Workbook
Dim ws As Excel.Worksheet
Dim iCol As Integer
Dim strName As String
Dim iIndex As Integer
Dim strPath As String
Dim strFile As String
strPath = "c:\temp\oldfiles\"
strFile = Dir(strPath & "*.xlsx")
Do While strFile <> ""
Set wb = Workbooks.Open(Filename:=strPath & strFile)
'Loop through the sheets.
For iIndex = 1 To Application.Worksheets.Count
Set ws = Application.Worksheets(iIndex)
'Loop through the columns.
For iCol = 1 To ws.UsedRange.Columns.Count
'Check row 1 of this column for the char of *
If InStr(ws.Cells(1, iCol).Value, "*") > 0 Then
'We have found a column with the char of *
ws.Columns(iCol).EntireColumn.Delete
End If
Next iCol
Next iIndex
wb.SaveAs Filename:="C:\temp\newfiles\" & wb.Name, FileFormat:=xlOpenXMLWorkbook
wb.Close SaveChanges:=False
strFile = Dir
Loop
End Sub