gpt4 book ai didi

vba - 在新记事本中写入文本

转载 作者:行者123 更新时间:2023-12-02 10:27:21 24 4
gpt4 key购买 nike

有人可以帮我将单元格值写入记事本的新实例吗?

这是我尝试过的代码:

Sub a()
Dim nt As String
nt = Shell("notepad.exe", vbNormalFocus)
Print #1, ActiveSheet.Cells(1, 1).Value
Close #1
End Sub

最佳答案

我很多年前在 vbforums.com 上回答过类似的问题,但找不到它,所以我很快为你重写了它。我已经对代码进行了注释,因此您在理解它时不会有任何问题。

就像你和我一样,我们都有名字,同样,窗口也有“句柄”(hWnd)、类等。一旦你知道 hWnd 是什么,与该窗口交互就更容易了。 Findwindow API 使用类名查找特定窗口的 hWnd。阅读其余 API Here

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long

Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, _
ByVal lpsz2 As String) As Long

Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long

Private Const WM_SETTEXT = &HC

Private Sub Command1_Click()
Dim Ret As Long, ChildRet As Long
Dim sString As String

'~~> This is the value from the cell which
'~~> you want to send to notepad
sString = Range("A1").Value

'~~> Start Notepad
Ret = Shell("notepad.exe", vbNormalFocus)

'~~> Wait for it to load
DoEvents

'~~> Find notepad
Ret = FindWindow(vbNullString, "Untitled - Notepad")

'~~> Check if found
If Ret = 0 Then
MsgBox "Cannot find Notepad Window"
Exit Sub
End If

'~~> Find the "Edit Window" which is a child window of Notepad window
ChildRet = FindWindowEx(Ret, ByVal 0&, "Edit", vbNullString)

'~~> Send the message
SendMessage ChildRet, WM_SETTEXT, 0, ByVal sString
End Sub

为了获取Windows的类名,我通常使用Spy++或uuSpy。看看这就是我如何使用 Spy++ 获取记事本的类名“Edit”

enter image description here

关于vba - 在新记事本中写入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33643803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com