2013-02-08 100 views
0

我想创建一个宏,可以在标题中找到特定的字符串,然后格式化该列中的单元格。例如,我有一个名为“购买日期”,“上限日期”和“交易日期”的标题。我希望能够找到所使用的“日期”的第一个实例,将它们格式化为文本,然后找到下一个发生和格式等。Excel VBA宏查找和格式

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

感谢您的任何帮助。

+4

_I已创建一个只能找到第一个实例_然后发布您的代码! – 2013-02-08 22:28:31

回答

0

我也努力过去第一次找到。来自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 

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

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

0

这不是特别优雅,但这很可能会为你做伎俩。只需编辑一些像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