我在处理某些数据时遇到了麻烦,可能会发生单元格为空的情况。例如,我们有两列,ID和值。 ID应始终正确,但值可能会丢失“值”。如果发生这种情况,那么我们应该在其位置添加一个0。
问题是我不知道如何将其添加到Application.Transpose(Range(Cells(1, 1), Cells(1, 1).End(xlDown)).Value2)
中,因为这是从工作表收集所有数据的唯一方法。
我需要这样做,因为数组的大小不一样,而且必须继续。
Dim xData() As Variant
For Each targetSheet In wb.Worksheets
With targetSheet
'Populate the array
xData(0) = Application.Transpose(Range(Cells(1, 1), Cells(1, 1).End(xlDown)).Value2)
xData(1) = Application.Transpose(Range(Cells(1, 2), Cells(1, 2).End(xlDown)).Value2)
End With
Next targetSheet
答案 0 :(得分:0)
就在收集数据之前,先在循环中填充空白单元格:)
<form name=method="post" action="">
<div class="listen">
<h2>Enter 6-digit code:</h2>
</div>
<div class="listen">
<input type="text" maxlength="6" id="code" placeholder="XXXXXX" name="6digit" />
</div>
<div class="listen">
<input class="orangebutton" id="opener" type="button" value="Proceed" onclick="checkFunc()" />
</div>
</form>
<div id="dialog-empty" title="Error">
<p>You have left field blank. Try again.</p>
</div>
<div id="dialog-error" title="Error">
<p>You have entered wrong code. Try again.</p>
</div>
<div id="dialog-success" title="Success">
<p>Congratulations! You will be proceeded to google.com.</p>
</div>
答案 1 :(得分:0)
填充0而不是空白单元格将解决此问题。 我也得到xData(0)行上的下标超出范围错误-如此声明的数组的长度为2。
Dim lngRow, i As Long
Dim xData(2) As Variant
For Each targetSheet In wb.Worksheets
With targetSheet
'Populate zeros
lngRow = .Cells(Rows.Count, 2).End(xlUp).Row
For i = 2 To lngRow //considering row 1 will have headers
If .Cells(i, 2) = "" Then .Cells(i, 2) = 0
Next
'Populate the array
xData(0) = Application.Transpose(.Range(.Cells(1, 1), .Cells(1, 1).End(xlDown)).Value2)
xData(1) = Application.Transpose(.Range(.Cells(1, 2), .Cells(1, 2).End(xlDown)).Value2)
Debug.Print UBound(xData(0))
Debug.Print UBound(xData(1))
End With
Next targetSheet
答案 2 :(得分:-1)
这个简单的VBA代码就能解决问题
在假定条件下,您的列值位于Excel列“ B”中,数据位于“ Sheet1”中
Private Sub fill_blanks_with_zeroes()
For Each cell in Sheets("Sheet1").Columns("B").Cells
If IsEmpty(cell) Then
cell.Value = 0
End If
Next cell
End Sub
您可以像这样在过程中调用它
Dim xData() As Variant
For Each targetSheet In wb.Worksheets
With targetSheet
'Populate the array
xData(0) = Application.Transpose(Range(Cells(1, 1), Cells(1, 1).End(xlDown)).Value2)
xData(1) = Application.Transpose(Range(Cells(1, 2), Cells(1, 2).End(xlDown)).Value2)
End With
Next targetSheet
Call fill_blanks_with_zeroes