vba如果单元格包含与文件名匹配的值,那么说ok,否则说不好?

时间:2014-11-14 13:29:09

标签: excel vba

我已经更新了我的代码,以便更多地解释我试图做的事情......

我正在生成一个带有数字和字母的随机字符串,并创建一个带有随机生成字符串名称的文本文件,在这种情况下我会调用我的字符串:strPassword

现在,一旦创建了文本文件,我想执行检查以查看该文件名是否存在。 所以这意味着检索创建并保存为文件名的随机字符串。

如果文件存在,我应该收到一条消息说好,否则应该说不行。

我正在尝试通过调用strPassword

来检索文件名

由于某种原因,它告诉我该文件不存在所以我只能假设它无法获得strPassword的值。它会在生成一个随机数时出现,它会忘记生成的内容,那么有没有办法可以将strPassword保存到变量或会话或某种内存以便稍后检查文件名?

当单击我的单元格A1时,它会检查文件名是否存在于单元格S32中,如果它不存在则显示一条消息,并且该文件是使用随机字符串strPassword创建并保存的。

然后,如果我想在单元格S32中键入此字符串名称,则应该说文件存在,因为它刚刚创建了它,但它的说法文件不存在。

例如,如果我有一个文本文件,其文件名由usiung strPassword随机生成,位于:

P:\XBQILGHD.txt

所以在我的单元格中,如果我要键入:

XBQILGHD (which is the strPassword value)

然后我会收到一条消息“OK”,否则我会收到一条消息,上面写着“不行”

有人可以告诉我这里我做错了什么吗? 感谢

    Dim strPassword As String
Dim i As Integer
For i = 1 To 10
If i Mod 2 = 0 Then
strPassword = Chr(Int((90 - 65 + 1) * Rnd + 65)) & strPassword
Else
strPassword = Int((9 * Rnd) + 1) & strPassword
End If
Next i


If Dir("P:\" & strPassword & ".txt") <> "" Then
MsgBox "File exists"
Else
MSG3 = MsgBox("Hi " & Range("N9").Value & "," & vbNewLine & vbNewLine & "Unfortunately you have used up your entire allowance for this month." & vbNewLine & vbNewLine & "You will not be able to continue with this request. Please wait until next month, when your request allowance will be reset." & vbNewLine & vbNewLine & "Think this is an Error?" & vbNewLine & "Contac us at NewSuppliers@Hewden.co.uk to make an appeal.", vbOKOnly, "Important Notice!")
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("P:\" & strPassword & ".txt", True)
a.WriteLine (strPassword)
a.Close
End If

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,请尝试:在文件ttp.txt中保存了你的pwd

    Dim strPassword As String
    Dim i As Integer
    For i = 1 To 10
    If i Mod 2 = 0 Then
    strPassword = Chr(Int((90 - 65 + 1) * Rnd + 65)) & strPassword
    Else
    strPassword = Int((9 * Rnd) + 1) & strPassword
    End If
    Next i


       If Dir("P:\ttp.txt") <> "" Then
       MsgBox "File exists"
       Else
       MSG3 = MsgBox("Hi " & Range("N9").Value & "," & vbNewLine & vbNewLine & "Unfortunately you have used   up your   `enter code here`entire allowance for this month." & vbNewLine & vbNewLine & "You will not be able to continue with this request. Please wait until next month, when your request allowance will be reset." & vbNewLine & vbNewLine & "Think this is an Error?" & vbNewLine & "Contac us at NewSuppliers@Hewden.co.uk to make an appeal.", vbOKOnly, "Important Notice!")
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("P:\ttp.txt", True)
a.WriteLine (strPassword)
a.Close

End If