简体   繁体   English

Excel VBA For Loop和Counter的嵌套IF语句

[英]Excel VBA For Loop and Nested IF statements for Counter

I have a value in a cell that should match the filename of a document in a directory. 我在一个单元格中具有一个值,该值应与目录中文档的文件名匹配。

Sheet3 Column A1 = C:\\Users\\Admin\\Desktop\\Folder1 Sheet3列A1 = C:\\ Users \\ Admin \\ Desktop \\ Folder1

Sheet3 Column A2 = test.xls Sheet3列A2 = test.xls

‘Location of directory
sCurrentXLDirectory = Worksheets("Sheet3").Cells(1, 1).Value
Set CurrentXLFSO = CreateObject("Scripting.FileSystemObject")
ProceedNow = True
Set CurrentXLFolder = CurrentXLFSO.GetFolder(sCurrentXLDirectory)
Set CurrentXLFiles = CurrentXLFolder.Files
‘Always 10 files in this folder
If CurrentXLFiles.Count <> 10 Then
   MsgBox "Wrong Directory or Folder Mismatch"
   ProceedNow = False
Else
'Return one for indentical filename
Dim NameCount As Integer
NameCount = 0
For Each folderIDX In CurrentXLFiles
 ‘Compare file names specified cell value
    If folderIDX.Name = Worksheets("Sheet3").Cells(1, 2).Value Then
    NameCount = NameCount + 1
        If NameCount <> 1 Then
            MsgBox "Unable to find file”
            ProceedNow = False
        End If
    End If
Next
End If

For some reason, even if I change test.xls to test1.xls, it will still do Proceed = True 由于某些原因,即使我将test.xls更改为test1.xls,它仍然会继续执行Proceed = True

If a nested IF statement is not the preferable way to do this, please guide me in the right direction. 如果嵌套IF语句不是实现此目的的首选方法,请引导我朝正确的方向发展。

If the purpose of the procedure is verify if a file exists or does not exist, using the Dir() function would be much simpler. 如果该过程的目的是验证文件是否存在,则使用Dir()函数将更加简单。

If this is the goal, try the following code: 如果这是目标,请尝试以下代码:

Sub test()
    Dim sDirectory As String
    Dim sFile As String

    sDirectory = Worksheets("Sheet3").Cells(1, 1).Value
    sFile = Worksheets("Sheet3").Cells(1, 2).Value
    sFile = Dir(sDirectory & "\" & sFile, vbDirectory)
    If Len(sFile) = 0 Then
        MsgBox "Unable to find file"
    End If
End Sub

The code you provided will not change a file name, so maybe this is just the beginnings of your attempt. 您提供的代码不会更改文件名,因此也许这只是您尝试的开始。 What I found, though, is that Range("A2") is "Cells(2, 1)", not "Cells(1, 2)", as you currently have it. 但是,我发现Range(“ A2”)是“ Cells(2,1)”,而不是“ Cells(1,2)”,就像您当前拥有的那样。 You are referencing cell B1, which probably does not contain a file name. 您正在引用单元格B1,它可能不包含文件名。

To alleviate such confusion in the future, always refer to one or the other, then such problems are avoided or easily diagnosed. 为了减轻将来的此类混乱,请始终一一提及,然后避免或轻松诊断此类问题。

Such as: 如:

If folderIDX.Name = Worksheets("Sheet3").Range("A2").Value Then

This should trip that "ProceedNow = False" flag that you are looking for. 这将触发您正在寻找的“ ProceedNow = False”标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM