我需要以制表符分隔文件的名称保存选择的。csv个文件。
我有以下代码来选择文件,指定定界符,然后遍历文件,一一打开并保存它们。
问题是迭代。
Sub sandbox2()
Dim xFilesToOpen As Variant
Dim i As Integer
Dim xWb As Workbook
Dim xTempWb As Workbook
Dim xDelimiter As String
Dim xScreen As Boolean
Dim strFileFullName As String
On Error GoTo ErrHandler
xScreen = Application.ScreenUpdating
Application.ScreenUpdating = False
xFilesToOpen = Application.GetOpenFilename("Text Files (*.*), *.*", , , , True)
xDelimiter = Application.InputBox("Delimiter: ", , ",")
If TypeName(xFilesToOpen) = "Boolean" Then
MsgBox "No files were selected", , "Sorry dude"
GoTo ExitHandler
End If
For i = 1 To UBound(xFilesToOpen)
Set xTempWb = Workbooks.Open(xFilesToOpen(i))
strFileFullName = Replace(ActiveWorkbook.FullName, ".csv", "")
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=strFileFullName + ".txt", FileFormat:=xlText, CreateBackup:=False
xTempWb.Close False
Application.DisplayAlerts = True
ActiveWorkbook.Close savechanges:=False
Set xTempWb = Nothing
Next i
ExitHandler:
Application.ScreenUpdating = xScreen
Set xWb = Nothing
Set xTempWb = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description, , "error"
Resume ExitHandler
End Sub
此代码适用于第一个文件,但随后出现错误
“对象变量或未设置块变量的情况”
查看文件夹时,第一个文件保存为。txt文件,但仅第一个保存。
您最好不要依赖任何active对象(在这种情况下为Workbook
,而是引用适当的对象实例,]
而且,您应该通过将Application.DisplayAlerts
设置为False
之前处理文件,并在ExitHandler块中将其设置移回到True
,并确保在出现任何错误时始终进行设置]。 >
所以我将按照以下说明去做:
Sub sandbox2() Dim xFilesToOpen As Variant Dim i As Long Dim xScreen As Boolean On Error GoTo ErrHandler xScreen = Application.ScreenUpdating Application.ScreenUpdating = False xFilesToOpen = Application.GetOpenFilename("Text Files (*.*), *.*", , , , True) xDelimiter = Application.InputBox("Delimiter: ", , ",") If TypeName(xFilesToOpen) = "Boolean" Then MsgBox "No files were selected", , "Sorry dude" Else Application.DisplayAlerts = False ' set it to 'False' only once before entering the loop For i = 1 To UBound(xFilesToOpen) With Workbooks.Open(xFilesToOpen(i)) ' open a workbook with current name and reference it .SaveAs Filename:=Replace(.FullName, ".csv", "") + ".txt", FileFormat:=xlText, CreateBackup:=False ' act on referenced workbook properties .Close False ' close referenced workbook End With Next i End If ExitHandler: Application.DisplayAlerts = True ' be sure to set it back to 'True' should any error take you out of your loop Application.ScreenUpdating = xScreen Exit Sub ErrHandler: MsgBox Err.Description, , "error" Resume ExitHandler End Sub
请注意,我摆脱了
Dim xTempWb As Workbook ' no longer used Dim xWb As Workbook ' never used .... Set xWb = Nothing ' never set Dim xDelimiter As String ' never used .... xDelimiter = Application.InputBox("Delimiter: ", , ",") ' never used
并且使用
Dim i as Long
,作为一般规则,不会发生任何溢出错误,因为整数最多可以达到32000 value or so