伙计们,我目前正在使用某些excel vba,但遇到一个问题,我一直试图将循环设置为一直运行到最后,但是由于某种原因,该功能无法正常工作。 或至少没有按我的要求运行。
Private Sub validar()
Dim src As Workbook
Dim last as long, k As long
Dim ref As String, nac As String, npc As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
folha = estadoform.Label1.Caption
lastnum = Application.ThisWorkbook.Worksheets(folha).Range("A65536").End(xlUp).Row
num = Application.ThisWorkbook.Worksheets(folha).Cells(lastnum, 6)
' ABRIR EXCEL
Set src = Workbooks.Open("U:\Mecânica\Produção\OEE\OEE ( FULL LOG )\OEEalerta.xlsx", True, False)
Sheets("alerta").Select
last = Workbooks("OEEalerta.xlsx").Sheets("alerta").Range(" A10000").End(xlUp).Row
For k = 1 To last
ref = .Cells(k, 2)
npc = .Cells(k, 4)
nac = .Cells(k, 5)
If num = ref And (nac < npc) Then
nac = nac + 1
End If
Next k
ErrHandler:
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.DisplayAlerts = False 'IT WORKS TO DISABLE ALERT PROMPT
'SAVES FILE USING THE VARIABLE BOOKNAME AS FILENAME
src.Save
Application.DisplayAlerts = True 'RESETS DISPLAY ALERTS
' CLOSE THE SOURCE FILE.
src.Close True ' FALSE - DON'T SAVE THE SOURCE FILE.
Set src = Nothing
End Sub
答案 0 :(得分:2)
好吧,我在这里猜。
首先,始终尝试为变量赋予有意义的名称。这是为了帮助您阐明意图。
此外,请不要忘记限定您正在访问的所有成员,例如Cells()。这非常重要,因为它可以更改程序的行为。所以,我会写src.Cells(...)而不是Cells(....)
您无需选择工作表即可对其进行读写。
在模块的开头使用Option Explicit。这样,您将必须明确声明所有变量,并避免一些常见错误,例如,错误地输入变量名称。
正如我评论的那样,您正在保存更改,但是您从未更改源工作簿。 另外,您正在对字符串值执行一些代数运算!
所以,这就是我的猜测:
Option Explicit
Private Sub validar()
Dim folha As Long ' sheet number
Dim src As Workbook ' a workbook from which alerts are being read
Dim lastRow As Long ' last row with content in a worksheet
Dim alertNum As Long ' Alert number being updated
Dim k As Long ' counter
Dim ref As String ' reference of the alert
Dim nac As Long ' nac ?
Dim npc As Long ' npc ?
Application.ScreenUpdating = False
On Error GoTo ErrHandler
folha = CLng(estadoform.Label1.Caption)
With ThisWorkbook.Worksheets(folha)
lastRow = .Range("A65536").End(xlUp).Row
alertNum = .Cells(lastRow, 6)
End With
' ABRIR EXCEL
Set src = Workbooks.Open("U:\Mecânica\Produção\OEE\OEE ( FULL LOG )\OEEalerta.xlsx", True, False)
With src.Sheets("alerta")
lastRow = .Range(" A10000").End(xlUp).Row
For k = 1 To lastRow
ref = .Cells(k, 2)
npc = .Cells(k, 4)
nac = .Cells(k, 5)
If ref = alertNum And (nac < npc) Then .Cells(k, 5) = nac + 1 ' update where the filter conditions are met
Next k
End With
ErrHandler:
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.DisplayAlerts = False 'IT WORKS TO DISABLE ALERT PROMPT
'SAVES FILE USING THE VARIABLE BOOKNAME AS FILENAME
src.Save
Application.DisplayAlerts = True 'RESETS DISPLAY ALERTS
' CLOSE THE SOURCE FILE.
src.Close False ' FALSE - DON'T SAVE THE SOURCE FILE (since it has already been saved)
Set src = Nothing
End Sub