Excelmacros的帮助 – 如果语句的variables范围

我正在创build一个macros来帮助组织数据转储(表单1)到发票(表单2)中。 我已经编码了大部分的macros,但我坚持以下。

我希望macros读取表1中的Y列,这是一个variables范围(可以是2行到50),并检查它是否显示“CB”。 如果这是真的,那么表2上的E11是是,否则否,等等,直到它到达表1的列Y的末尾。

我有以下几点:

Sheets("Data_Dump").Select intCounter = 1 While Range("Y" & (intCounter + 1)) <> "" intCounter = intCounter + 1 Wend intCardSize = intCounter MsgBox (intCardSize) Sheets("Data_Dump").Select If Range("Y" & intCardSize) = "CB" Then Sheets("Reconciliation").Select Range("E11:E" & intCardSize).Select Range("E11") = "Yes" End If 

虽然范围似乎工作,它显示列Y中的文本单元格的数量,但我似乎无法包装我的头围绕如何让它从Y1移动到Y2等等,然后粘贴到E11的响应然后E12等等。

你遇到的问题是你的代码不会循环去尝试比较。 While循环只能查看下一个单元格中是否有内容。 事实上,它实际上跳过了第一行,但也许这是故意的。

 Dim dataSheet As WorkSheet Dim recSheet As Worksheet Dim lngCounter As Long 'Use long because an integer may not be big enough for large dataset. Dim intCardSize As Long Set dataSheet = ThisWorkbook.Sheets("Data_Dump") Set recSheet = ThisWorkbook.Sheets("Reconciliation") 'You want to set the sheets to a variable instead of referring to the whole path each time 'Also, Note the usage of "ThisWorkbook" which guarantees the worksheet 'is coming from the one with code in it. lngCounter = 2 'If you want to start looking at row 2, start at row 2 with 'the variable instead of starting the variable and checking var+1 While dataSheet.Range("Y" & (lngCounter)) <> "" 'While there is a value in the column 'intCardSize = intCounter 'Not sure what this is supposed to do 'MsgBox (intCardSize) 'This looks like debugging. Commenting out. If dataSheet.Range("Y" & lngCounter) = "CB" Then 'Check each row as you go through the loop. 'Sheets("Reconciliation").Select 'Avoid selecting sheet/range. Unneccessary work for computer. recSheet.Range("E" & (9 + lngCounter)) = "Yes" 'Set reconciliation sheet value to "Yes" if data sheet has "CB" 'The reconciliation sheet starts on row 11, whereas the datasheet 'starts at row 2 ,a difference of 9 Else recSheet.Range("E" & (9 + lngCounter)) = "No" 'Otherwise set to no. End If lngCounter = lngCounter + 1 Wend intCardSize = lngCounter - 1 'It's been increased to one past the last item. MsgBox intCardSize 'Display the last row checked. 

我希望我能理解你的代码目标如下

 With Sheets("Data_Dump") With Sheets("Reconciliation").Range("E11").Resize(.Cells(.Rows.Count,1).Row) .Formula="=IF('Data_Dump'!Y1="CB", "Yes","")" .Value= .Value End With End With