循环逻辑和字典中的条件

时间:2018-05-23 15:05:42

标签: excel vba excel-vba

我正在循环一个字典,然后将它输出到活动表格的前2张图片,然后为接下来的两张照片创建另外的表格,依此类推。每张纸只需要2张图片,具体取决于字典中可能有多少张图片。我需要逻辑方面的帮助,因为我不确定如何将循环编码为仅在将前2个添加到活动工作表后才放2张图片。

下面是代码:

Dim PictureFilename As Variant
Dim FileList As Dictionary
....
For Each PictureFilename In FileList
    i = i + 1
    If i >2 then
        TabName = DefaultWorksheetNameAdder + " " + Format(Now(), "mm-dd-yyyy")
        PicWorkbook.Sheets.Add(after:=PicWorkbook.Sheets(PicWorkbook.Sheets.Count)).Name = "NewSheet"
        Set PicWorksheet = PicWorkbook.Sheets(PicWorkbook.Sheets.Count)

        'how to handle the next two without having to code i > 4 , i > 6 ect.?
    Else
        Set Photo = PicWorksheet.Shapes.AddPicture(CStr(PictureFilename), msoFalse, msoCTrue, 1, 1, -1, -1)
        Set pic = Nothing
        Set pic = Photo
        colPictures.Add pic
    End If
Next

3 个答案:

答案 0 :(得分:0)

结帐MOD

if i MOD 2 = 0 then...

MOD生成数字的模数。

0 MOD 2为0

1 MOD 2是1

2 MOD 2为0

3 MOD 2是1

4 MOD 2为0

答案 1 :(得分:0)

这对你有用吗?

Dim PictureFilename As Variant
Dim FileList As Dictionary
....
i = 0
For Each PictureFilename In FileList '''Assuming you have a worksheet already.
    If i > 1 then
        TabName = DefaultWorksheetNameAdder + " " + Format(Now(), "mm-dd-yyyy")
        PicWorkbook.Sheets.Add(after:=PicWorkbook.Sheets(PicWorkbook.Sheets.Count)).Name = "NewSheet"
        Set PicWorksheet = PicWorkbook.Sheets(PicWorkbook.Sheets.Count)
        i = 0
    Else
        Set Photo = PicWorksheet.Shapes.AddPicture(CStr(PictureFilename), msoFalse, msoCTrue, 1, 1, -1, -1)
        Set pic = Nothing
        Set pic = Photo
        colPictures.Add pic
        i = i + 1
    End If
Next

答案 2 :(得分:0)

Mod是你的朋友。我重新编写了一些代码,但这应该可以满足您的需求:

Dim PictureFilename As Variant
Dim FileList As Dictionary

i = 0

For Each PictureFilename In FileList
    i = i + 1

    If i > 2 And i Mod 2 = 1 Then
       TabName = DefaultWorksheetNameAdder + " " + Format(Now(), "mm-dd-yyyy")
       PicWorkbook.Sheets.Add(after:=PicWorkbook.Sheets(PicWorkbook.Sheets.Count)).Name = "NewSheet"
       Set PicWorksheet = PicWorkbook.Sheets(PicWorkbook.Sheets.Count)
    End If

    Set Photo = PicWorksheet.Shapes.AddPicture(CStr(PictureFilename), msoFalse, msoCTrue, 1, 1, -1, -1)
    Set pic = Nothing
    Set pic = Photo
    colPictures.Add pic
Next