2017-02-14 223 views
2

我目前正在複製數據表格excel到記事本,併成功使用excel VBA函數SendKeys從Excel複製數據到記事本

但我正在尋找任何可以幫助我避免使用sendkeys的工作。

我有這樣的代碼的那一刻:只

sub test() 

    dim wb as Workbook 
    set wb = "C:\Documents\test.xlsx" 
    wb.Sheets(2).Range("C2:C" & lRow).Copy 
    myApp = Shell("Notepad.exe", vbNormalFocus) 
    SendKeys "^v" 
    Application.CutCopyMode = False 
    wb.Sheets(2).Range("C2:C" & lRow).NumberFormat = "@" 
end sub 

這一個副本從Excel到記事本中的數據,但在Excel文件中做了一些修正之後,我想要的數據在記事本複製到從C2開始再次複製到excel。

+2

是否有您所使用的記事本一個特殊的原因 - 將在文本文件在別的地方使用?如果你只是在尋找某個地方「存儲」一些數據,而你做了其他的事情,那麼你可能會更好地把它放入一個數組中。 –

+0

你是否試圖複製沒有公式的值?我想不出有什麼好的理由從記事本粘貼和複製。 – Slai

+0

@Slai是的,我只是複製值並再次粘貼到Excel表。 – ramedju

回答

2

您可以使用文件系統對象寫入到一個文本文件:

Dim fso as Object 
Set fso = CreateObject("Scripting.FileSystemObject") 

Dim oFile as Object 
Set oFile = FSO.CreateTextFile(strPath) 

oFile.WriteLine "test" 

oFile.Close 
Set fso = Nothing 
Set oFile = Nothing 

欲瞭解更多信息請看這裏:https://technet.microsoft.com/en-us/library/ee198716.aspx

3

這是一種替代過程SendKeys

  • 從工作表上的一組單元格中獲取值

  • 拷貝到剪貼板

  • 獲取剪貼板中的內容轉換爲字符串

  • 保存該字符串臨時文件

  • 打開Notepad.exe的與臨時文件的內容

代碼:

Option Explicit 

Sub OpenNotepadWithTempFileWithClipboardContent() 

    Dim rngData As Range 
    Dim strData As String 
    Dim strTempFile As String 

    ' copy some range values 
    Set rngData = Sheet3.Range("B1:B5") 
    rngData.Copy 

    ' get the clipboard data 
    ' magic code for is for early binding to MSForms.DataObject 
    With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}") 
     .GetFromClipBoard 
     strData = .GetText 
    End With 

    ' write to temp file 
    strTempFile = "D:\temp.txt" 
    With CreateObject("Scripting.FileSystemObject") 
     ' true to overwrite existing temp file 
     .CreateTextFile(strTempFile, True).Write strData 
    End With 

    ' open notepad with tempfile 
    Shell "cmd /c ""notepad.exe """ & strTempFile & """", vbHide 

End Sub 
1
'This macros may solve your problem 
    Sub SaveMySheetAsTextFile() 
     Sheets("Sheet1").Select 
     ActiveWorkbook.SaveAs Filename:="C:\mynotepadfile.txt", FileFormat:=xlText 
    End Sub 
2

有點太晚了,但你可以將數據複製到剪貼板,並粘貼文本(測試和工程):

Dim r As Range 
Set r = wb.Sheets(2).Range("C2:C" & lRow) 
r.Copy 

With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}") 
    .GetFromClipboard 
    Application.CutCopyMode = False 
    .PutInClipboard 
End With 

r.Select 
r.NumberFormat = "@" 
r.Worksheet.PasteSpecial "Text" 
+0

謝謝。這就是我所做的:) – ramedju

相關問題