如果Cell为空,则为条件

时间:2016-04-23 10:59:23

标签: vba ms-word word-vba

我的代码有问题。它无法识别Empty Cell

条件是“如果单元格为空则重复,否则更改当前单元格上方单元格中文本的字体”

Sub lastprice()
    Dim price As String
    Do
        Selection.Find.ClearFormatting
        With Selection.Find.Font
            .Size = 11
            .Bold = True
        End With
        With Selection.Find
            .Text = "last price ("
            .Forward = True
            .Wrap = wdFindStop
            .Format = True
        End With
        Selection.Find.Execute

        If Selection.Find.Found = False Then
            Exit Do
        Else
            Selection.MoveRight Unit:=wdCell
            price = Trim(Selection.Text)

            If price <> "" Then ' I think there is some problem
                Selection.MoveLeft Unit:=wdCell, Count:=2
                Selection.Font.Name = "Cambria"
                Selection.MoveDown Unit:=wdLine, Count:=1
            Else
            End If
        End If
    Loop
End Sub

有关详细信息,请查看

应该通过具有条件的表格的第二张图片来详细说明

2 个答案:

答案 0 :(得分:1)

我在调试器中使用了您应该完成的代码,并检查了price是什么。事实证明它包含某种带有字符代码13,7的单元格标记。因此,仍然在Word中的空单元格包含某些内容。将您的if语句更改为以下内容:

If mid(price,1,1) <> Chr(13) Then

答案 1 :(得分:0)

编辑后:@paul ogilvie

 If mid(price,1,1) = Chr(13) Then

对我有用,我将逻辑<>更改为=

这是工作代码

Sub lastprice()
Dim price As String
Do
Selection.Find.ClearFormatting
With Selection.Find.Font
    .Size = 11
    .Bold = True
End With
With Selection.Find
    .Text = "last price ("
    .Forward = True
    .Wrap = wdFindStop
    .Format = True
End With
Selection.Find.Execute
If Selection.Find.Found = False Then
  Exit Do
  Else
    Selection.MoveRight Unit:=wdCell
    Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend
   price = Trim(Selection.Text)
   If Mid(price, 1, 1) = Chr(13) Then
    Selection.MoveLeft Unit:=wdCell, Count:=2
    Selection.Font.Name = "Cambria"
    Selection.MoveDown Unit:=wdLine, Count:=1
   Else
    Selection.MoveRight Unit:=wdCharacter, Count:=1
   End If
   End If
Loop
End Sub