我試圖檢測並處理掉我的數據中的「重置」。數據應該一直在增加,但有時傳感器喜歡重置到更低的值。我想檢測這些並通過將當前值與先前值相加來糾正它們以獲得當前值。在單元格中循環並在必要時覆蓋它們在VBA中
例子:
1
2
5
10
11
100
150
2
3
5
應該是:
1
2
5
10
11
100
150
152
153
155
下面是對我工作的一個Python實現:
def process(arr):
max_before_reset = 0
reset_detected = False
old = arr[:]
for i, e in enumerate(old): # enumerate contains original array
if i == 0:
continue
if e < old[i-1]:
print '\t', e, old[i-1]
max_before_reset = arr[i-1]
reset_detected = True
if(reset_detected):
arr[i] = old[i] + max_before_reset
print old
return arr
a = [97, 99, 100, 2, 3, 5, 6, 4, 3];
print process(a)
這需要在VBA做的,所以我把一拍即合:
Sub ProcessData_test(ByVal RawColumn As String, ByVal ProcessedColumn As String)
Dim NumRows As Integer
Dim MaxBeforeReset As Integer
Dim ResetDetected As Boolean
Const ps As String = "test2"
Const rds As String = "test1"
MaxBeforeReset = 0
ResetDetected = False
With Sheets(rds)
NumRows = .Range(RawColumn & .Rows.Count).End(xlUp).Row
End With
'MsgBox NumRows
For i = 1 To NumRows
If i = 1 Then
Else
If Worksheets(rds).Range(RawColumn & i).Value < Worksheets(rds).Range(RawColumn & i).Value Then
MaxBeforeReset = Worksheets(ps).Range(ProcessedColumn & (i - 1)).Value
ResetDetected = True
End If
If ResetDetected Then
Worksheets(ps).Range(ProcessedColumn & i).Value = Worksheets(rds).Range(RawColumn & i).Value + MaxBeforeReset
End If
End If
Next i
End Sub
Sub Test()
Dim a As String, b As String
a = "A"
b = "A"
Call ProcessData_test(a, b)
End Sub
但由於某種原因,它不會修改test2工作表中的單元格。我似乎無法弄清楚爲什麼。有任何想法嗎?
您是否嘗試一步一步調試VBA代碼,或者至少使用'Debug.Print'添加更多反饋,例如:'Debug.Print「對於i =」&i&「rds value」&Worksheets(rds ).Range(RawColumn&i).Value&「與」&Worksheets(rds).Range(RawColumn&i).Value「等比較。如果你放置了足夠的這些,你可以看到代碼是否曾經進入過任何If'聲明(或解釋爲什麼不)等 – Ralph