【发布时间】:2015-03-04 04:51:14
【问题描述】:
我在直接从具有某些值的数据库中提取的 Excel 表中有不同的分数。我想从 excel 中提取这些分数,并能够使用 if 语句更改 word 文档中的文本(例如,如果单元格中的分数(2、2)> 60(在 excel 中)=删除/替换某个文本(在 word 中))用VBA。有谁知道我将如何编译这个宏?
我试过的代码:
Private Sub CommandButton8_Click()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Set exWb = objExcel.Workbooks.Open("C:\Desktop\Testdoc.xlsx")
If score.Cells(2, 2) >= 60 Then
Function FnOpeneWordDoc()
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("C:\Desktop\TestDoc.docm")
objWord.Visible = True
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "text here"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
End Function
End If
exWb.Close
Set exWb = Nothing
End Function
编辑:新代码:
Private Sub CommandButton7_Click()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Set exWb = objExcel.Workbooks.Open("C:\UsersDesktop\Testdoc.xlsx")
If exWb.Sheets(1).Cells(2, 2).Value >= 60 Then Run [BLA]
If Not exWb.Sheets(1).Cells(2, 2).Value >= 60 Then Run [BLA2]
End If
exWb.Close
Set exWb = Nothing
End Sub
Function BLA()
With Selection.Find
.ClearFormatting
.Text = "Old text"
.Replacement.ClearFormatting
.Replacement.Text = ""
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
End Function
Function BLA2()
With Selection.Find
.ClearFormatting
.Text = "Old text"
.Replacement.ClearFormatting
.Replacement.Text = "Old text"
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
End Function
【问题讨论】:
-
向我们展示您的一些代码!你试过什么?
-
学习VBA的最佳方法是什么?
-
我希望这能让它更清楚一点...我不知道该怎么做。
-
请解释什么不工作,什么和在哪里?任何错误(编号和描述)?
-
另外,使用“F8”或其他调试选项(如断点)逐行运行代码应该可以帮助您了解正在发生的事情以及错误的确切位置。