我正在将一个关闭的工作簿保存为单独的工作表中的.csv文件,以便在minitab中打开。将每个单独的工作表保存为.csv的代码工作得很好。问题是我还需要在将其保存为.csv之前删除每个工作表的顶行,而不影响原始文件。
代码将在第一次迭代中工作,第一张表的.csv文件是正确的。但是一旦我进入第二个循环,我在删除顶行的代码行上得到错误。
这些错误都在下面的代码中列出,旁边是我尝试过的变体。
我是VBA的新手,我觉得我缺少了一些基本的东西。有人能帮我吗?谢谢。
Dim objExcel
Dim objWB
Dim objws
Dim myPath As String
Dim i As Integer
Dim row As Integer
Dim col As Integer
Set objExcel = CreateObject("Excel.Application")
Set objWB = objExcel.Workbooks.Open("file location")
'prevent overwrite warnings
Application.DisplayAlerts = False
i = 1
For Each objws In objWB.Worksheets
myPath = "\\G:\file location"
objExcel.ActiveWorkbook.Worksheets(i).Copy
'objExcel.ActiveWorkbook.Worksheets(i).Activate 'if this segment of code is active, it also gets Sub script out of range on second loop
objExcel.ActiveWorkbook.Worksheets(i).Range("a1").EntireRow.Delete 'run-time error 9 Sub script out of range on second loop
'objExcel.ActiveWorkbook.Worksheets(1).Range("a1").EntireRow.Delete 'run-time error 1004 Delete method of range class failed on second loop
'objExcel.ActiveWorkbook.objws.Range("a1").EntireRow.Delete 'error object doesn't support this property or method
objExcel.ActiveWorkbook.SaveAs Filename:=myPath & objws.Name, FileFormat:=xlCSV, CreateBackup:=False
objExcel.ActiveWorkbook.Close False
i = i + 1
Next
objExcel.ActiveWorkbook.Close True
Application.DisplayAlerts = True
1条答案
按热度按时间8ehkhllq1#
可能有两个问题:
objExcel.ActiveWorkbook.Worksheets(i).Copy
应该是objws.Copy
。1.然后,
objExcel.ActiveWorkbook.Worksheets(1).Rows(1).Delete
删除复制的工作表中的第一行。注意,
i
可能是多余的。