我是 Visual Basic 的新手,也是一名会计师,所以如果这个问题太简单,我很抱歉。我似乎正在努力寻找并寻找下一个结构。
我正在尝试查找总账代码并在其旁边放置从查找表获取的另一个代码。例如,72001...我试图让系统返回该范围,然后将一个单元格向左移动并从另一个单元格放置该数字 - 比方说 240。最终结果将是左侧单元格上的 240(拉出)来自另一个单元格上的表格)和右侧单元格上的 72001。
我试图通过在子程序中创建较小的代码块来简化问题,但即使在基础级别上,我仍然很难理解 find/findnext 的概念。此时我只是测试该功能,但它仍然没有达到我想要的效果;我不明白这是为什么。
Sub abc()
Dim A As Range
Do While Not A Is Nothing
Set A = Range("B1:B100").Find(what:="A")
MsgBox (A)
Loop
End Sub
当 A 不是空数据集时,代码不应该继续循环吗?我在 B 列上放置了一堆“A”,但我仍然没有收到任何消息框。为什么什么也没发生?我什至试图把“不”去掉,但什么也没发生(没有双关语)。我不明白。
我已经尝试了上面的代码,但没有成功,下面的代码(如下)。对于上面的内容,我不会收到错误,除非我去掉“不”,这是我不明白的。我也尝试了以下方法,但得到了令人沮丧的“对象错误使用无效”。我只是想用查找函数替换 A 字符。
Sub abc()
Dim A As Range
Dim B As Range
Set A = Range("B1:B100").Find(what:="A", after:="A1")
If A Is Not Nothing Then A.Value = Z
Else
Do Until Not B Is Nothing
Set B = Range("B:B100").Find(what:="A", after:="A1")
MsgBox ("A")
Loop
End Sub
Find
方法相当复杂。Sub abc()
Const SearchString As String = "A"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
Dim rg As Range: Set rg = ws.Range("B1:B100")
' The following will attempt to find in a cell equal to "A".
' It will starting looking in cell `B1`, after the supplied last cell 'B100'
' since the default parameter of 'SearchDirection' is 'xlNext'.
' It will find "a" and "A" since the default parameter of 'MatchCase'
' is 'False'.
Dim cell As Range: Set cell = rg.Find(What:=SearchString, _
After:=rg.Cells(rg.Cells.Count), LookIn:=xlValues, LookAt:=xlWhole)
Dim FirstAddress As String
If Not cell Is Nothing Then
' Store the address of the first found cell in a variable.
FirstAddress = cell.Address
Do
' It is advisable, when you're developing a loop, to use
' 'DoEvents' so you can exit an endless loop with 'Esc'
' or 'Pause/Break'.
DoEvents
' Do something with the found cell.
MsgBox "Found """ & cell.Value & """ in cell """ _
& cell.Address(0, 0) & """.", vbInformation
' Find the next cell equal to "A". Note how you are supplying
' the current cell as the parameter for the 'After' argument
' so it will start by looking into the next cell.
Set cell = rg.FindNext(After:=cell)
' Since 'Find' or 'FindNext' will try to find 'forever',
' from 'B1' to 'B100', and again, and again, you need to compare
' the address of the newly found cell with the address of the first
' found cell to be able to exit the loop once it got back
' to the first found cell.
Loop While cell.Address <> FirstAddress
'Loop Until cell.Address = FirstAddress
Else
MsgBox "No """ & SearchString & """ was found.", vbExclamation
End If
End Sub