Excel格式的代码适用于第一个文件,但不适用于第二个文件

我有三个内容和结构非常相似的Excel文件。 在我可以使用这些文件之前,需要对这些文件进行一些格式化步骤。 使用Access VBA,我已经开发了一些代码来删除某些行,并对数据执行TextToColumnsfunction。

此代码适用于第一个电子表格。 但是,我发现第二个错误:

运行时错误“91”:对象variables或块variables未设置

这发生在代码的Selection.TextToColumns ...行(即上面的操作对第二个电子表格执行正常)。

任何想法为什么发生这种情况?

在审查这篇文章后 ,我虽然也许我需要在TextToColumns之前添加,或者可能以不同的方式定义范围。 但是,我缺乏VBA知识变得非常明显!

 Private Sub FormatFile(sPath As String) Dim oExcel As Excel.Application Dim owb As Workbook Dim oWS As Worksheet Dim sFile As String Dim sDirectory As String Dim rng As Range Set oExcel = New Excel.Application Set owb = oExcel.Workbooks.Open(sPath) Set oWS = owb.Sheets(1) Debug.Print oWS.Name oExcel.Visible = False DoCmd.SetWarnings False sDirectory = fGetDirectory(sPath) sFile = fGetFileName(sPath) oWS.Rows(5).Delete oWS.Rows(3).Delete oWS.Rows(2).Delete oWS.Rows(1).Delete DeleteLastRow oWS.Columns("A") oWS.Columns("A:A").Select Selection.TextToColumns Destination:=oWS.Range("A1"), DataType:=xlDelimited, TextQualifier:=-4142, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar:="|", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True owb.Save owb.Close oExcel.Quit Set owb = Nothing Set oWS = Nothing Set rng = Nothing Debug.Print "created file " & sFile DoCmd.SetWarnings True Set oExcel = Nothing End Sub 

这可能与使用.Select (build议您避免使用 )有关。

改变你的线

 oWS.Columns("A:A").Select Selection.TextToColumns Destination:=oWS.Range("A1"), DataType:=xlDelimited, TextQualifier:=-4142, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar:="|", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True 

 oWS.Columns("A:A").TextToColumns Destination:=oWS.Range("A1"), DataType:=xlDelimited, TextQualifier:=-4142, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar:="|", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True 

可能发生的是,select不被select,所以当使用select时,它不是“那里”。