简体   繁体   English

access vba中的excel替换功能

[英]excel replace function in access vba

I am trying to run some excel vba code inside access vba.我正在尝试在访问 vba 中运行一些 excel vba 代码。 It almost work but i have problem with replace function.它几乎可以工作,但我有替换功能的问题。 Can anyone look at code belowe and tell me what is wrong?任何人都可以查看下面的代码并告诉我有什么问题吗?

Sub test2()
Dim lngColumn As Long
Dim xlx As Object, xlw As Object, xls As Object, xlc As Object
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim blnEXCEL As Boolean

blnEXCEL = False

' Establish an EXCEL application object
On Error Resume Next
Set xlx = GetObject(, "Excel.Application")
If Err.Number  0 Then
    Set xlx = CreateObject("Excel.Application")
    blnEXCEL = True
End If
Err.Clear
On Error GoTo 0
xlx.Visible = True

' Replace C:\Filename.xls with the actual path and filename
' of the EXCEL file from which you will read the data
Set xlw = xlx.Workbooks.Open("Q:\21 Projekty\FlowControl\Flow.xlsx", , True) ' opens in read-only mode

' Replace WorksheetName with the actual name of the worksheet
' in the EXCEL file
Set xls = xlw.Worksheets("Flow")

' Replace A1 with the cell reference from which the first data value
' (non-header information) is to be read
Set xlc = xls.range("A1") ' this is the first cell that contains data

With xls
    .Columns(2).Insert Shift:=xlToRight
    SelectedColumn = SelectedColumn + 1

    .Columns(3).Copy _
        Destination:=.Columns(1)

    .Columns(2).Replace What:=" - *", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False 
'Error there  Subscript out of range (Error 9) 

    .Columns(3).Replace What:="* - ", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

    .Columns(2).AutoFit
    .Columns(3).AutoFit
Errorhandling:
    'Application.ScreenUpdating = True
    'End Sub
End With
End Sub

As has already been said you need to deal with the Excel VBA constants like xlToRight.如前所述,您需要处理像 xlToRight 这样的 Excel VBA 常量。

One way to do that is to substitute the constants for their values, another is to declare them as constants at the top of your code like this.一种方法是用常量替换它们的值,另一种方法是像这样在代码的顶部将它们声明为常量。

Const xlToRight = -4161
Const xlPart = 2
Const xlByRows = 1

Problem was a little bit diffrent Replace function in excel vba and access vba.问题有点不同 excel vba 和 access vba 中的替换功能。 Now i only use:现在我只使用:

.columns(2).Replace What:=" - *", Replacement:=""

Problem solved.问题解决了。

EDIT:编辑:
It sholud be应该是

.columns(2).Replace What:="* - ", Replacement:="", LookAt:=2, _
        SearchOrder:=1, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM