使用For每个循环都无法遍历工作表

时间:2014-01-27 17:32:51

标签: excel vba

您好我一直在尝试将几个宏连接在一起以自动执行一个过程,该过程涉及从文本导入数据文件并将部分数据复制到“核心表”。当我尝试使用“For Each循环”在纸张中移动检查条件并且如果满足条件时运行数据提取宏,我的问题就出现了。基本上宏不循环,我研究了各种解决方案但没有任何效果。它第一次运行时工作正常(通常显示的纸张符合条件,因此它移动到“shima”宏)然后显示“核心表”,因为这不符合我想要的条件它继续下一张,但事实并非如此。代码如下,如果有任何不清楚,请告诉我。

Sub FullAuto()


Call Module1.Myfolderselector 'this macro imports all the text file in a given folder

Dim Msg, Style, Title, Response, MyString
Public ws As Worksheet


Msg = "Yes for Fluorescence, No for UV"
Style = vbYesNo + vbCritical + vbDefaultButton1
Title = "Choose data"
'this parts asks the user which type of Data they want to import

Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
   MyString = "Yes"
Else
   MyString = "No"
End If


For Each ws In Worksheets 'this is the part with issues.

    If MyString = "Yes" And Range("A1").Value <> "Core" Then
    Call Module1.Detector_B_Shima_9_0
    ElseIf MyString = "No" And Range("A1").Value <> "Core" Then
    Call Module1.Detector_A_Shima_9_1

    End If

Next ws

Worksheets.Add(After:=Worksheets(1)).Name = "Plot Sheet"


End Sub 

Sub Detector_B_Shima_9_0()


Cells.Select
    Selection.Find(What:="[LC Chromatogram(Detector B-Ch1)]", After:=ActiveCell _
    , LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, MatchCase:=False).Activate

ActiveCell.Offset(9, 1).Select
ActiveCell.Value = Range("B20")
Range(ActiveCell, Cells(ActiveCell.Row + 8401, ActiveCell.Column)).Select

Selection.Copy
Sheets("Core Sheet").Select
Range("C3").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
ActiveCell.EntireColumn.Insert

End Sub

1 个答案:

答案 0 :(得分:2)

尝试更改此代码:

For Each ws In Worksheets 'this is the part with issues.

    If MyString = "Yes" And Range("A1").Value <> "Core" Then
    Call Module1.Detector_B_Shima_9_0
    ElseIf MyString = "No" And Range("A1").Value <> "Core" Then
    Call Module1.Detector_A_Shima_9_1

    End If

Next ws

到下一个

For Each ws In Worksheets 

    If MyString = "Yes" And ws.Range("A1").Value <> "Core" Then
        Call Module1.Detector_B_Shima_9_0
    ElseIf MyString = "No" And ws.Range("A1").Value <> "Core" Then
        Call Module1.Detector_A_Shima_9_1
    End If

Next ws

请注意,我在ws.之前添加了Range("A1")ws.Range("A1").Value。这个小小的改进有助于VBA理解,Range("A1")属于工作表ws