Excel / VBA - 检测服务器是否可达 [英] Excel/VBA - Detect if server is reachable
问题描述
\\myserv\\ \\ MyFolder
,但是对于PC处于不同的子网,我到达服务器的唯一方法是使用IP (即\\1.2.3.4 \\
我只是想在VBA中,如果有任何方式我可以说:
如果我可以使用 \\myserv
找到服务器,然后使用 myserv
否则使用 1.2.3.4
?
不幸的是我根本无法调整网络,我想设置以至于当IP发生变化时,我的大多数用户仍然可以通过访问 \\myserv\MyFolder
来使用该工具。
解决方案假设你在Windows环境中,这里有一个替代方法(没有实际的代码):
- 在Excel VBA中,使用SHELL函数执行Net View功能并将输出发送到文件。即:
Dim vsFileName
vsFileName = C:\Temp\RandomFileName.txt
Shell(Net View \\\myServ>& vsFileName)
- 之后,检查输出的文件大小。如果输出文件大小为0,表示找到路径。如果找不到路径,输出文件大小将为0。
如果FileLen(vsFileName)= 0,则vsNetworkPath =1.2.3.4
- 通过以下方式清理自己:
Kill(vsFileName)
如果您不想使用win32函数,这是另一种选择。每次运行代码时都要随机选择文件名以避免冲突,这是一个好主意。
At my work place, different computers are in different subnets, and if the PCs are in the same subnet as the Samba server, I can reach the file server by going to \\myserv\MyFolder
, but for the PC is in a different subnet, the only way for me to reach the server is by using IP (i.e., \\1.2.3.4\MyFolder)
.
I am just wondering in VBA, if there is any way I can say:
if I can find the server using \\myserv
, then use myserv
, else use 1.2.3.4
?
Unfortunately I can not tweak the network at all and I want to set up this way so that at least when the IP changes, majority of my users could still use the tool by visiting \\myserv\MyFolder
.
解决方案 Assuming you are on Windows environment, here's an alternative approach (without the actual code):
- In Excel VBA, use the SHELL function to execute a Net View function and send the output to a file. ie:
Dim vsFileName
vsFileName = "C:\Temp\RandomFileName.txt"
Shell("Net View \\myServ > " & vsFileName )
- After that, check the filesize of the output. If output file size > 0, meaning the path is found. If the path cannot be found, the output filesize will be 0.
If FileLen( vsFileName ) = 0 Then vsNetworkPath = "1.2.3.4"
- Clean up after yourself by:
Kill( vsFileName )
This is an alternative if you don't want to mess around with win32 functions. It's a good idea to randomize the filename each time you run the code to avoid clashes.
这篇关于Excel / VBA - 检测服务器是否可达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!