我刚刚开始使用VBA,每个错误及其母亲都不断弹出。这是最新的一个,因为它是一个外部对象,我想我必须要找到的文档是广泛的。如果您愿意指出阻止代码运行的原因(以及您可能看到的任何其他错误)。
我以前在java中编程,所以我有一个合理的概念把握,知道我想做什么。我对使用我的方法更有效率的模糊方法不感兴趣。我只是想让它发挥作用。我相当肯定我的主要问题是有错误阻止它执行,所以,请再次指出它们。
Sub findRawMaterial()
Dim currentSheet As String
currentSheet = "Sheet1"
Dim currentProduct As String
Dim blankTest As Boolean
blankTest = False
Dim currentRow As Integer
currentRow = 2
Dim currentProductNumber As String
Dim currentMaterialNumber As String
Dim rowAmount As Integer
rowAmount = 10
Do While blankTest = False
currentProductNumber = CStr(Worksheets("Sheet2").WorksheetFunction.Trim(Cells(currentRow - 2, 2).Value))
currentMaterialNumber = CStr(Worksheets("Sheet2").WorksheetFunction.Trim(Cells(currentRow - 2, 5).Value))
Dim i As Integer
For i = 4 To rowAmount
If currentProductNumber = WorksheetFunction.Trim(Cells(i, 1)) Then
If IsEmpty(Range("C" + CStr(i)).Value) Then
Set Cells(i, 3).Value = currentMaterialNumber
Else
Rows(currentRow + 1).Insert.EntireRow
Set Range("C" + CStr(i + 1)).Value = currentMaterialNumber
End If
End If
Next i
If IsEmpty(Range("W" + CStr(currentRow))) Then
blankTest = True
End If
currentRow = currentRow + 1
Loop
Dim index As Integer
End Sub
答案 0 :(得分:1)
我可以看到你收到错误的原因 您将单元格指向位置(0,2) 为了您的信息,列A行1的位置是(1,1) 而且,workheetFunction不支持这样的“修剪” 我为你做了修正。希望有所帮助
currentProductNumber = CStr(Worksheets("Sheet2").WorksheetFunction.Trim(Cells(currentRow - 2, 2).Value))
currentMaterialNumber = CStr(Worksheets("Sheet2").WorksheetFunction.Trim(Cells(currentRow - 2, 5).Value))
正确的应该是:
currentProductNumber = CStr(Trim(Worksheets("Sheet2").Cells(currentRow - 1, 2).Value))
currentMaterialNumber = CStr(Trim(Worksheets("Sheet2").Cells(currentRow - 1, 5).Value))
答案 1 :(得分:0)
.Cells
和.Range
引用的工作表父级(即.
或全停)。CStr
转换都是不必要的。此外,使用Trim
将输出字符串值。这是您提供的代码的快速重写。
Sub findRawMaterial()
Dim currentSheet As String, currentProduct As String
Dim blankTest As Boolean
Dim currentProductNumber As String, currentMaterialNumber As String
Dim i As Long, rowAmount As Long, currentRow As Long
Dim wf: Set wf = Application.WorksheetFunction
currentSheet = "Sheet1"
currentRow = 2
rowAmount = 10
blankTest = False
With Worksheets("Sheet2")
Do While blankTest = False
currentProductNumber = wf.Trim(.Cells(currentRow - 1, 2).Value2)
currentMaterialNumber = wf.Trim(.Cells(currentRow - 1, 5).Value2)
For i = 4 To rowAmount
If currentProductNumber = wf.Trim(.Cells(i, 1)) Then
If IsEmpty(.Range("C" + i).Value) Then
.Cells(i, 3).Value = currentMaterialNumber
Else
.Rows(currentRow + 1).Insert.EntireRow
.Range("C" + i + 1).Value = currentMaterialNumber
End If
End If
Next i
If IsEmpty(Range("W" + currentRow)) Then
blankTest = True
End If
currentRow = currentRow + 1 'should this be incremented before checking column W?
Loop
End With
Dim index As Integer ' what is this doing here
End Sub
关于我无需查看样本数据就可以做的所有事情。