我在网上搜索过,似乎找不到我需要的确切解决方案。我有一个第三方程序,它以.csv格式生成报告。不幸的是,当您直接在Excel中打开.csv文件时,格式会出现时髦,A列中有一些数据,B列中有一些数据。但是,如果您在记事本中打开.csv,然后将其粘贴到Excel,数据很好。我有以下代码将在记事本中打开该文件,但不知道如何选择并将其复制到Excel中的单元格A1。非常感谢您的帮助。
Dim FileToOpen
If MsgBox("Please open the file you wish to import, and be patient. The macro will take 3-5 minutes to run.", _
vbOKOnly, "Navigate") = 1 Then
FileToOpen = Application.GetOpenFilename("Text Files (*.csv),*.csv")
FileToOpen = Shell("Notepad.exe " & FileToOpen, 1)
End If
答案 0 :(得分:1)
要回答您的问题,您可以使用SendKeys(如果没有使用等待时间,或者其他应用程序干扰,则sendkeys不健全):
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("ReadText") 'whatever your worksheet is
'your code here
FileToOpen = Shell("Notepad.exe " & FileToOpen, 1)
waitTime (2000) 'as an alternative
AppActivate FileToOpen, False
Application.SendKeys "^a", True 'sends select all command keys
waitTime (500)
Application.SendKeys "^c", True 'sends copy keys
waitTime (500)
ws.Activate
ws.Paste Range("A1")
' rest of code
Public Function waitTime(ms As Long)
Application.Wait Now() + (ms / 24 / 60 / 60 / 1000)
End Function
答案 1 :(得分:0)
这些是未经测试的,但我发现了一些想法here:
尝试调整:
Sub ImportText()
Dim Text
Dim i As Long
Application.ScreenUpdating = False
'put your own path below
Open ActiveWorkbook.Path & "\MYFILE.txt" For Input As #1
i = 1
Do While Not EOF(1) ' Loop until end of file.
Input #1, Text
Range("a" & i) = Text
i = i + 1
Loop
Close #1
End Sub
(这也是SO before)
或者
Dim myPlace as Range
Set myPlace = Cells(1,1)
Workbooks.OpenText Filename:=ActiveWorkbook.Path & "\MYFILE.txt", DataType:=xlDelimited, Tab:=True
ActiveSheet.UsedRange.Copy Destination:=myPlace
ActiveWorkbook.Close
我不知道第二个是否会起作用,因为它只是按分界导入,如上所述,看起来并不漂亮。但是我把它留下来以防它出于某种原因起作用。