【问题标题】:Excel VBA Macro Find and FormatExcel VBA 宏查找和格式化
【发布时间】:2013-04-20 02:02:15
【问题描述】:

我正在尝试创建一个可以在标题中找到特定字符串的宏,然后格式化该列中的单元格。例如,我有一个名为“Purchase Date”、“Cap Date”和“Exp Date”的标题。我希望能够找到使用的“日期”的第一个实例,将它们格式化为文本,然后找到下一个出现和格式等。

我创建了一个只会找到第一个实例,然后不再查找的实例。任何想法?我查找了“查找”和“之后”,但无法让它们正常工作。

感谢您的帮助。

【问题讨论】:

  • 我创建了一个只会找到第一个实例的实例 - 然后发布您的代码!

标签: excel vba find format


【解决方案1】:

我也挣扎着越过第一个发现。从 Do While 中查看下面代码的最后一部分。也许你可以从中有所收获。

Sub HyperLinking()     
  Call HyperLink("Text TO Hyperlink", "C:\Document.docx")   
End Sub 

Private Function HyperLink(LinkName As String, LinkAddress As String) 
  Dim WDApp As Object, wd As Object, rn As Long 
  On Error Resume Next 
  Set WDApp = GetObject(, "Word.Application") 
  If Err.Number <> 0 Then 
      Set WDApp = CreateObject("Word.Application") 
  End If 
  On Error Goto 0 
  Set wd = WDApp.Documents.Open(LinkAddress) 
  WDApp.Visible = True 
  Set objWdRange = wd.Content      
  objWdRange.Find.ClearFormatting 
  With objWdRange.Find 
      .Text = LinkName 
      .Forward = True 
      .Wrap = wdFindContinue 
  End With 
  Do While objWdRange.Find.Execute = True 
      objWdRange.Hyperlinks.Add Anchor:=objWdRange, Address:=LinkAddress, SubAddress:="", ScreenTip:="Linked  Document", TextToDisplay:=LinkName 
      objWdRange.Find.Execute 
  Loop      
  wd.Save 
  wd.Close 
  Set wd = Nothing 
  Set WDApp = Nothing      
End Function

一个问题是,有时,我猜由于格式的原因,所有的单词都找不到。也许有人可以帮助解释为什么会发生这种情况?

您可以根据您的要求调整此代码。

【讨论】:

    【解决方案2】:

    它不是特别优雅,但这很可能会为您解决问题。只需编辑一些硬编码值,例如 sheetname,并确保您的列数不超过 99 列或行数不超过 999 行。

    Public Sub FormatRowsInDateColumns()
    Dim header As String
    
    Worksheets("Sheet1").Activate
    
    'loop through columns
    For col = 1 To 99
    
        'check if header cell contains word date
        header = Cells(1, col).Value
        If InStr(1, header, "date", vbTextCompare) <> 0 Then
    
            'convert cell values to string
            For Row = 1 To 999
                'Formats value and perserves as text with an apostrophe
                Cells(Row, col).Value = "'" & Format(Cells(Row, col).Value, "yyyy/mm/dd")
            Next Row
    
            'set column format as text
            Columns(col).NumberFormat = "@"
        End If
    Next col
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多