3

我正在尝试编写一个 VBA 程序,在文本文件中搜索用户名以查找用户的 IP 地址。例如,给定下面的输入,如果我搜索Chris Trucker我想192.168.130.22在消息框中看到。

> 192.168.2.151,Super Fly,ABC\Flys,2012-05-18 16:11:29 
> 192.168.2.200,Rain,ABC\rain,2012-05-17 15:42:05 
> 192.168.2.210,Snow,ABC\Snow,2012-05-16 08:24:39 
> 192.168.2.78,Wind,ABC\wind,2012-05-02 19:24:06 
> 192.168.130.21,Mike Jordan,ABC\Jordanm,2012-05-18 17:28:11 
> 192.168.130.22,Chris Trucker,ABC\Truckerc,2012-05-18 17:28:11 
> 192.168.130.23,Chris Jackson,ABC\JacksonC,2012-05-18 17:04:39

尝试了以下,但它是 VBScript

Const ForReading = 1

Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = "JacksonC"  

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("\\server\tsusers\Users.txt", ForReading)

Do Until objFile.AtEndOfStream
    strSearchString = objFile.ReadLine
    osakapc = Left(strSearchString,14)
    Set colMatches = objRegEx.Execute(strSearchString)

    If colMatches.Count = 1 Then 
        For Each strMatch in colMatches  


        Next
    End If
Loop
4

4 回答 4

3

这是我的做法:

Option Explicit

Sub tester()
    Dim inputFilePath As String
    inputFilePath = "\\server\tsusers\Users.txt"

    MsgBox GetUserIpAddress("Chris Trucker", inputFilePath) 
                            ' or "JacksonC" or "Bozo" or whatever

End Sub

Function GetUserIpAddress(whatImLookingFor As String, _
    inputFilePath As String)
    Const ForReading = 1

    Dim foundIt As Boolean
    Dim thisLine As String
    Dim ipAddress As String
    Dim FSO As Object
    Dim filInput As Object

    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set filInput = FSO.OpenTextFile(inputFilePath, ForReading)

    foundIt = False
    Do Until filInput.AtEndOfStream
        thisLine = filInput.ReadLine
        If InStr(thisLine, whatImLookingFor) <> 0 Then
            foundIt = True
            ipAddress = Replace((Split(thisLine, ",")(0)), "> ", "")
            Exit Do
        End If
    Loop

    If foundIt Then
        GetUserIpAddress = ipAddress
    Else
        Err.Raise 9999, , _
            "I stiiiiiiiill haven't foooouuuund what I'm looking for."
    End If
End Function

如您所见,如果未找到用户名,此函数将引发错误。

请注意,此功能允许您搜索长格式 ( Chris Trucker) 或短格式 ( Truckerc) 甚至时间戳 ( 2012-05-18 17:28:11) 的用户名。但请注意,如果您的搜索词有多个实例,则只会返回与第一个实例对应的 IP 地址。如果您希望返回所有实例,您可以调整代码。

作为最后的评论,建议始终声明所有变量并通过Option Explicit在代码顶部强制自己这样做。

于 2012-05-23T06:55:04.333 回答
3

功能

Private Function ReturnNames(fPath$, pName$) As String
    'this This example uses **Microsoft VBScript Regular Expressions 5.5** and **Microsoft Scripting Runtime**
    Dim result$
    Dim re As New RegExp, fso As New FileSystemObject
    If fso.FileExists(fPath) = True Then
        Dim contents$, mt As Match, mts As MatchCollection
        contents = fso.OpenTextFile(fPath, ForReading).ReadAll
        With re
            .Global = True
            .MultiLine = True
            .Pattern = "^> *([^,\r\n]+),([^,\r\n]+),([^,\r\n]+),([^,\r\n]+)$"
            If .test(contents) = True Then
                Set mts = .Execute(contents)
                For Each mt In mts
                    If LCase(mt.SubMatches(1)) = LCase(pName) Then
                        result = mt.SubMatches(0)
                        Exit For
                    End If
                Next mt
            End If
        End With
        If result = "" Then
            result = "No matches found for '" & pName & "'."
        End If
    Else
        result = "File not found."
    End If

    ReturnNames = result

End Function

可能会被调用

Public Sub test000()
    MsgBox ReturnNames("C:\Documents and Settings\Patel_81\Desktop\1.txt", "Chris Trucker")
End Sub
于 2012-05-23T06:57:51.440 回答
0

您必须创建一个 FileSystemOject 并调用 ReadLine 方法。像这样的东西。

http://www.visualbasicscript.com/Vbscript-to-read-txt-file-for-input-m31649.aspx

要获取 IP 地址和名称,请通过传递 ',' 作为参数调用 InStr 函数。

vibscript 中的字符串函数

http://www.w3schools.com/vbscript/vbscript_ref_functions.asp

于 2012-05-23T05:38:50.697 回答
0

多么精美的分隔文本文件啊!

假设您提供了文件格式,并且您传入了文件中实际存在的名称,此函数将返回您提供的任何名称的 IP 地址:

Function GetIPAddress(fileName As String, userName As String) As String

  Dim userinfo As String
  Dim tokens As Variant
  Dim laststring As Variant
  Dim userIP As String

  ' read text file into string
  userinfo = GetText(fileName)
  ' remove everything after the name we are looking for
  tokens = Split(userinfo, userName)(0)
  ' get the second-to-last comma-delimited value
  laststring = Split(tokens, ",")(UBound(Split(tokens, ",")) - 1)
  ' split by > and get second element
  userIP = Trim$(Split(laststring, ">")(1))

  GetIPAddress = userIP
End Function

使用Charley Kyd 的这个函数:

Function GetText(sFile As String) As String
  Dim nSourceFile As Integer, sText As String
  ''Close any open text files
  Close
  ''Get the number of the next free text file
  nSourceFile = FreeFile
  ''Write the entire file to sText
  Open sFile For Input As #nSourceFile
  sText = Input$(LOF(1), 1)
  Close
  GetText = sText
End Function

样品用法:

Sub testgetip()
  Debug.Print GetIPAddress("\\server\tsusers\Users.txt", "Chris Trucker")
End Sub

如果名称在目标文件中不存在,当然会抛出错误(运行时错误 9)。

另一种可能的方法:

Function GetIPAddress(fileName As String, searchTerm As String) As String

  Dim userinfo As String
  Dim tokens As Variant
  Dim i As Long
  Dim userIP As String

  ' read text file into string
  userinfo = GetText(fileName)
  ' split text file by line breaks
  tokens = Split(userinfo, vbCrLf)

  ' loop through array and look for line that contains search term
  For i = LBound(tokens) To UBound(tokens)
    If InStr(tokens(i), searchTerm) > 0 Then  ' found it
      ' get first element of comma-split string, then second element of space-split string
      GetIPAddress = Split(Split(tokens(i), ",")(0), " ")(1)
      Exit For
    End If
  Next i
End Function

也使用Charley Kyd 网站上的功能。

这个稍微好一点,因为如果没有找到搜索词,它不会抛出错误,它只会返回一个空值,您需要在调用代码中对其进行测试。与 Jean 的代码一样,它还允许您搜索任何术语,而不仅仅是用户名。

样品用法:

Sub testgetip()
  Dim ipaddr As String
  ipaddr = GetIPAddress("\\server\tsusers\Users.txt", "Trucker")

  If Len(ipaddr) = 0 Then
    MsgBox "Could not find IP address for that search term"
  Else
    Debug.Print ipaddr
  End If
End Sub
于 2012-05-24T00:41:46.970 回答