Excel vba格式并查找问题

vwkv1x7d  于 2023-06-30  发布在  其他
关注(0)|答案(1)|浏览(133)

我有一些非常简单的代码,我想找到D列中%符号所在的行。所以i应该是4(显然),但我不知道如何克服运行时错误91。
提前感谢您的提示。

Dim a As Integer
Dim b As Integer
Dim i As Integer

a = 4
b = 5

Worksheets(1).Range("D4") = (a / b) * 100
Worksheets(1).Range("D4").NumberFormat = "0.00\%"

' run time error 91 occures in the following line    
i = Worksheets(1).Range("D:D").Find(What:="%", After:=Range("D1"), LookAt:=xlPart, SearchDirection:=xlNext).Row
' result of i
Range("A1")=i
p4tfgftt

p4tfgftt1#

查找列中最顶部的百分比格式单元格

...或包含百分比符号。

  • 阅读罗里和蒂姆·威廉姆斯的评论并记住它们。
    (工作簿和)工作表变量
Sub Test()
    
    Dim a As Long: a = 4
    Dim b As Long: b = 5

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Worksheets(1)

    ws.Range("D4").Value = (a / b) * 100
    ws.Range("D4").NumberFormat = "0.00\%"
    
    Dim cell As Range: Set cell = ws.Range("D:D").Find(What:="%", _
        After:=ws.Cells(ws.Rows.Count, "D"), LookIn:=xlValues, LookAt:=xlPart)

    If cell Is Nothing Then
        ws.Range("A1").Value = ""
        MsgBox "Could not find """ & "%" & """ in column D.", vbCritical
    Else
        ws.Range("A1").Value = cell.Row
        MsgBox "Found """ & "%" & """ in cell """ & cell.Address(0, 0) & """.", _
            vbInformation
    End If

End Sub

With语句

Sub TestWith()
    
    Dim a As Long: a = 4
    Dim b As Long: b = 5
    
    With ThisWorkbook.Worksheets(1)
        
        .Range("D4").Value = (a / b) * 100
        .Range("D4").NumberFormat = "0.00\%"
        
        Dim cell As Range: Set cell = .Range("D:D").Find(What:="%", _
            After:=.Cells(.Rows.Count, "D"), LookIn:=xlValues, LookAt:=xlPart)
    
        If cell Is Nothing Then
            .Range("A1").Value = ""
        Else
            .Range("A1").Value = cell.Row
        End If
            
    End With

End Sub

相关问题