我正在编写一些代码,这些代码将在按下按钮时运行,打开一个.csv文件(从另一个程序导出),复制一些信息,然后将其粘贴到第一个文件中。在某些时候(只有一部分),它实际上会粘贴来自其他文件的信息。似乎在打开另一个文件时发生这种情况,但是不一致。我尝试查看它是否与顶部的窗口有关,还是与我使用的最后一个窗口有关,但是仍然不一致。使用此工作表的用户很有可能会打开多个文件。
Public Sub getData()
Dim vFile As Variant
Dim wbCopyTo As Workbook
Dim wsCopyTo As Worksheet
Dim wbCopyFrom As Workbook
Dim wsCopyFrom As Worksheet
Set wbCopyTo = ActiveWorkbook
Set wsCopyTo = ActiveSheet
Dim SCOBlankLine As Integer
Dim importBlankLine As Integer
Dim importLastLine As Integer
'-------------------------------------------------------------
'Open file with data to be copied
vFile = Application.GetOpenFilename("Excel Files (*.csv*)," & _
"*.xl*", 1, "Select Excel File", "Open", False)
'If Cancel then Exit
If TypeName(vFile) = "Boolean" Then
Exit Sub
Else
Set wbCopyFrom = Workbooks.Open(vFile)
Set wsCopyFrom = wbCopyFrom.Worksheets(1)
End If
Debug.Print vFile
Debug.Print wbCopyFrom.FullName
Debug.Print wsCopyFrom.Name
提取错误信息时的最后调试值:
filepath \ lc_equip_20180816103532.csv
filepath \ lc_equip_20180727090447.csv
lc_equip_20180727090447
想法?
答案 0 :(得分:0)
基于发现它正在使用最近打开的文件的信息,我选择使用其他方法来打开文件并激活工作簿。此后尝试了许多文件打开组合,但尚未失败。
对于任何有兴趣的人:
'-------------------------------------------------------------
'Open file with data to be copied
vFile = Application.GetOpenFilename("Excel Files (*.csv*)," & _
"*.xl*", 1, "Select Excel File", "Open", False)
'If Cancel then Exit
If TypeName(vFile) = "Boolean" Then
Exit Sub
Else
Workbooks.Open Filename:=vFile
Set wbCopyFrom = Application.ActiveWorkbook
Set wsCopyFrom = wbCopyFrom.Worksheets(1)
End If
Debug.Print vFile
Debug.Print wbCopyFrom.FullName
Debug.Print wsCopyFrom.Name