循环创建工作簿

时间:2017-11-20 10:38:48

标签: excel vba excel-vba

您正在处理过滤数据并复制到新工作簿。我不能在新工作簿中重命名为mayday(在字符串中添加整数值)并获取type mismatch error - 请帮助需要做的事情

Sub ButtoClick()
Dim wbs2 As Worksheet
Dim wkb As Workbook
Dim strpath As String
Set wbs2 = Workbooks("Nov Collections-CF").Worksheets("Nov Collections-CF")
 Dim myday As Integer

     strpath = ("C:\Users\ashokkumar.d\Desktop\New folder (2)\")
    ran = ThisWorkbook.ActiveSheet.Range("A1:A16")

        For Each cel In ran
            myday = Day(cel)
            dDate = DateSerial(Year(cel), Month(cel), Day(cel))
            Set wkb = Workbooks.Add
            wkb.SaveAs FileName:=(strpath + "Nov Collections-CF" + myday + ".xlsx") 'Type Mismatch Error
            wbs2.Range("A1:K1").AutoFilter Field:=4, Criteria1:=Format(dDate, "dd/mm/yyyy"), Operator:=xlFilterValues

            wbs2.UsedRange.SpecialCells(xlCellTypeVisible).Copy
             With wkb.Sheets(1).Range("A1")
                    .PasteSpecial xlPasteFormats
                    .PasteSpecial xlPasteValues
                End With

            wkb.Save
            wkb.Close
        Next

End Sub

3 个答案:

答案 0 :(得分:1)

尝试与&符号连接,如下所示:

 wkb.SaveAs FileName:=(strpath & "Nov Collections-CF" & myday & ".xlsx") 

此外,您可以添加转换功能:

 wkb.SaveAs FileName:=(strpath & "Nov Collections-CF" & Cstr(myday) & ".xlsx") 

答案 1 :(得分:0)

当您尝试使用“+”

添加数字和字符串时,VBA可能会感到困惑

更改

wkb.SaveAs FileName:=(strpath + "Nov Collections-CF" + myday + ".xlsx")

改为

wkb.SaveAs FileName:=(strpath & "Nov Collections-CF" & myday & ".xlsx")

答案 2 :(得分:0)

如果要与+连接,则应确保所有值都是字符串。 myday被声明为整数。因此,尝试“字符串化”它:

wkb.SaveAs Filename:=(strpath + "Nov Collections-CF" + CStr(myday) + ".xlsx")