我正在尝试自动化一个过程,该过程涉及在 Excel 中使用 VBA 通过 RDP 在远程桌面上打开文件。我已经成功地登录到 RDP,但现在我很难始终如一地打开文件。我编写了一些依赖于 SendKeys 的代码,这些代码可能在 10% 的时间内有效,但我正在寻找更强大的东西。
Sub RunRDP()
Dim RetVal As Variant
Dim Target As String
Dim Sheet As Variant
'Log-in info
Target = "AAAA.com"
UserName = "BBBBBB\CCC"
Pwd = "DDDDD"
'Connect to Remote Desktop
RetVal = Shell("cmdkey /generic:""" & Target & """ /user:""" & UserName & """ /pass:""" & Pwd & """", 3)
RetVal = Shell("c:\Windows\System32\mstsc.exe /v:" & Target, 3)
'Press yes through cert errors
Do
If InStr(ActiveWinTitle, "Remote Desktop Connection") > 0 Then
Application.SendKeys "y", True
End If
Loop Until InStr(ActiveWinTitle, "AAAA") > 0
Application.Wait (Now + TimeValue("00:00:03"))
If InStr(ActiveWinTitle, "Remote Desktop Connection") > 0 Then
AppActivate "AAAAA.com - Remote Desktop Connection"
Else
AppActivate "AAAAA.com"
End If
Application.Wait (Now + TimeValue("00:00:07"))
上面的代码按预期工作。 ActiveWinTitle 是一个获取当前窗口标题的函数,见下图:
Public Declare Function GetForegroundWindow Lib "user32" _
() As Long
Public Declare Function GetWindowText Lib "user32" _
Alias "GetWindowTextA" (ByVal HWnd As Long, _
ByVal lpString As String, ByVal cch As Long) As Long
Public Function ActiveWinTitle() As String
Dim WinText As String
Dim HWnd As Long
Dim L As Long
HWnd = GetForegroundWindow()
WinText = String(255, vbNullChar)
L = GetWindowText(HWnd, WinText, 255)
ActiveWinTitle = Left(WinText, InStr(1, WinText, vbNullChar) - 1)
End Function
下面的代码是我试图打开文件的工作。其英文解释如下:
Application.SendKeys "RE", True
Application.SendKeys "~", True
Application.Wait (Now + TimeValue("00:00:01"))
Application.SendKeys "{F4}", True
Application.Wait (Now + TimeValue("00:00:01"))
Application.SendKeys "{BS}{BS}{BS}{BS}{BS}{BS}{BS}{BS}{BS}{BS}{BS}F:\[**FILEPATH HERE**]~", True
显然这是非常不可靠的,这也是我正在寻找更好的东西的原因。
这段代码是我在工作中使用的,并希望与我的同事分享——因此,我无法下载任何程序来代替 VBA 使用。
我看了这些问题没有多大用处:
Script to Open a batch file on a remote computer
我不熟悉 WMI,不确定是否必须完全替换使用 RDP。我试着查看它的文档,它完全超出了我的想象。
Run a batch file on a remote desktop from VBA
这是来自同一用户的较早线程。它有一些我无法关注的死链接。
我查看了很多与我有相同未回答问题的线程。这可能是徒劳的,但我想明确知道这是否可以管理。 [编辑:我在下面的研究中发现的一些未答复的论坛帖子]
提前感谢您的所有帮助。
最佳答案
非编程方法也会对您有所帮助吗?
在远程计算机上,创建一个计划任务,该任务在有人连接到用户 session 时启动。
...然后简单地从那里运行任何东西。
当然,也许您仍然只想接触高级技术,但有时只能通过使用现有工具轻松避免它们。
关于excel - 使用 VBA 在远程桌面上打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53562268/