繁体   English   中英

VBA:如何删除特定文件夹中的列“A”,其中不同的文件具有不同的工作表名称

[英]VBA: How to delete Column “A” in a specific Folder with different files with Sheet name that varies

我的桌面上有一个文件夹,其中包含或多或少的2000个csv文件。 这些文件只有1个“工作表”,但工作表名称有所不同。 唯一类似的事情是它以“Tankard”这个词开头。

在那一张表中,我只需删除所有2000个文件的Column A并保存它。 这是我第二个月在工作中探索vba自动化。 如果有人可以帮助我,我会很感激。 提前致谢。

脚本:

Sub Tank()
Dim wb As Workbook
Dim myPath As String
Dim myfile As String
Dim myExtension As String
Dim SheetName As String
'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

SheetName = "Tankard*"
  myPath = "\\ph00winfdfs01p\shares\JoeyC\documents\Roaming\Windows\Desktop\Tank\"
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "Tankard*.csv"

'Target Path with Ending Extention
  myfile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
For i = 1 To 201
Set wb = Workbooks.Open(Filename:=myPath & myfile)
';;;;;;;;;;;;;;WRITE YOUR CODE HERE
Sheets("SheetName").Select
Columns("A").Select
Selection.Delete
wb.Close SaveChanges:=True

Next i
'Get next file name
myfile = Dir

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

试着了解发生了什么。 此子目前所做的是打开Dir可以找到的第一个工作簿,打开它201次并每次删除工作表“Sheetname”的第一列。

Sheets("SheetName").Select

这将选择名称为"Sheetname" ,而不是具有您将字符串Sheetname设置为的值的名称。 如果有的话,它应该是Sheets(Sheetname)但是通配符在这里不起作用。

现在让我们来看看你想要实现的过程。

myfile = Dir(myPath & myExtension)

myfile设置为与您的模式匹配的第一个文件...\\Tankard*.csv

Set wb = Workbooks.Open(Filename:=myPath & myfile)

打开文件,现在您可以通过wb访问工作簿

要删除工作表上的第一列,我建议您选择所有内容但直接删除范围:

wb.Sheets(1).Columns(1).Delete 'If you want to actually delete the column
wb.Sheets(1).Columns(1).Clear  'If you want to just remove the values

如您所见,您根本不需要工作表的名称。 现在保存工作簿:

wb.Close SaveChanges:=True

现在您可以使用Dirmyfile设置为下一个文件名:

myfile = Dir

然后重复一遍,直到没有更多的文件(此时Dir将返回"" 。实现这一目标的最佳方法是使用While循环,例如像这样

While myfile <> ""
    'Do stuff here
Wend '(While End)

For循环的优点是您不需要知道文件夹中的确切文件数。

我会把它留给你来修补所有这些。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM