【发布时间】:2017-01-31 22:36:48
【问题描述】:
我要做的是仅使用基于另一个工作表上特定列中的某些值的记录来填充新工作表。到目前为止,我已经能够填充整个工作表,而无需仅填充我想要的记录。
工作表“完整视图”中有一个名为“更新状态”(C 列)的列,其值为“无更改”、“已更新”、“新建”、“已关闭”。我只需要在下面填充的新工作表中选择那些记录,其中只有那些在“更新状态”列中具有诸如无更改、已更新、新建等值的记录。但是,当我运行此代码时,它给了我一个空白的工作簿,即使完整视图工作簿中的值具有其他值而不是 C 列中的关闭值。有人可以帮忙吗? 提前感谢您的帮助!
Sub Scatterplot()
Dim headers() As Variant
Dim ws As Worksheet
Set ws = Worksheets("Scatterplot Excel Template")
'Clean Contents
ws.Cells.ClearContents
ws.Cells.Interior.ColorIndex = 0
Sheets("New Risk Template").Range("B3:B4").ClearContents
'Assign headers
headers = Array("Record ID", "ID", "Title", "Summary", "Primary Risk Type", "Secondary Risk Type", _
"Primary FLU/CF Impacted", "Severity Score", "Likelihood Score", "Structural Risk Factors")
With ws
For I = LBound(headers()) To UBound(headers())
.Cells(1, 1 + I).Value = headers(I)
Next I
Dim book1 As Worksheet
Dim lookFor As Range
Set book1 = Worksheets("Full View")
Set lookFor = book1.Range("B2:X1000")
Dim row_count As Integer
Dim col_count As Integer
'Find the last row and column number
Dim col_name As String
Dim record_id As String
Dim col_index As Integer
row_count = book1.Range("C" & Rows.Count).End(xlUp).Row
If book1.Cells(row_count, "C") = "Updated" And book1.Cells(row_count, "C") = "No Change" And book1.Cells(row_count, "C") = "New" Then
'Loop for input values
For I = 2 To row_count
ws.Cells(I, 1).Value = book1.Cells(I + 1, 2).Value
ws.Cells(I, 2).Value = Right(ws.Cells(I, 1).Value, 4)
For j = 3 To 10
On Error Resume Next
col_name = ws.Cells(1, j)
record_id = ws.Cells(I, 1)
col_index = Sheets("Full View").Cells(2, 1).EntireRow.Find (What:=col_name, _
LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False).Column
ws.Cells(I, j).Value = Sheets("Full View").Cells(I + 1, col_index).Value
Next
Next
End if
【问题讨论】:
-
首先检查“如果 book1.Cells(row_count, "C") = "Updated" 和 book1.Cells(row_count, "C") = "No Change" 和 book1.Cells(row_count, "C") = "New" Then":不应该所有的 "And" 都是 "Or"。
-
您还可以使用
Select Case book1.Cells(row_count, "C") | Case is = "Updated","No Change","New"使所有IFs更具可读性(管道表示行分隔...) -
大家好,感谢您的回复。我确实尝试了这两种选择。现在我得到了所有的记录,而不是只有那些应该只有 'Updated' , 'New' 和 'No Change' 值的记录。关于如何解决它有什么想法吗?
标签: vba excel if-statement