代码未成功循环通过工作表

时间:2014-10-03 08:35:41

标签: excel vba loops

这个VBA 2007代码可以完成这项工作,但是对于第一个工作表,它不会循环遍历工作簿的其余工作表(在那里他正在寻找一个值,并且它在第一个工作表中没有返回错误表,但它不应该)。任何人都可以建议我为什么?非常感谢你

Set sourcewb = Workbooks.Open(Filename:=direccionArchivo)
 chakal = sourcewb.Index
               guapo = sourcewb.Worksheets.Count
                 For z = chakal To guapo
                    Set ws = Sheets(z)
                        sourcewb.Columns(1).Value =  Application.WorksheetFunction.Clean(sourcewb.Columns(1))
                         Set gCell = ws.Columns("A").Find(what:=IDPEDIDO, LookIn:=xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False, searchformat:=False)

                            If Not gCell Is Nothing Then
                              'OTHER CODE NOT DISPLAYED
                            end if
                       Next z

                    Set gCell = Nothing

2 个答案:

答案 0 :(得分:0)

我认为它应该是这样的,尽管它仍然不起作用。

Set sourcewb = Workbooks.Open(Filename:=direccionArchivo)
chakal = 1
guapo = sourcewb.Worksheets.Count
For z = chakal To guapo
   Set ws = sourcewb.Sheets(z)

   'This will not work, clean expects a string not a range (a column is a range)
   ws.Columns(1).Value =  Application.WorksheetFunction.Clean(ws.Columns(1))


   Set gCell = ws.Columns("A").Find(what:=IDPEDIDO, LookIn:=xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False, searchformat:=False)

   If Not gCell Is Nothing Then
      'OTHER CODE NOT DISPLAYED
   end if
Next z
Set gCell = Nothing

答案 1 :(得分:0)

首先,clean函数对完整列不起作用。你必须循环遍历列中的每个单元格并使用worksheetfunction.clean(cell.value)。其次,您没有使用工作表的正确对象模型,即workbook.worksheets.range。我已更正您的代码,如下所示:

Sub t()
Dim sourcewb As Workbook
Dim ws As Worksheet

Set sourcewb = Workbooks.Open(Filename:=direccionArchivo)
           guapo = sourcewb.Worksheets.Count
             For Z = 1 To guapo
                Set ws = sourcewb.Sheets(Z)
                    endrow = ws.Cells(Rows.Count, 1).End(xlUp).Row
                        For Each cell In ws.Range(ws.Cells(1, 1), ws.Cells(endrow, 1))
                            WorksheetFunction.Clean (cell)
                        Next cell
                     Set gCell = ws.Columns("A").Find(what:=IDPEDIDO, LookIn:=xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False, searchformat:=False)

                        If Not gCell Is Nothing Then
                          'OTHER CODE NOT DISPLAYED
                        End If
                   Next Z

                Set gCell = Nothing
End Sub