我想从特定的工作簿中获取数据(有几十个工作簿,循环部分工作正常),但下面的代码不起作用,因为工作表是西里尔字母,并且它们给出了值'???????'到 sheet As String
参数。我想问如何在不打开工作簿的情况下强制重命名它(没有 Workbook.Open(WorkbookNum1)
因为在这种情况下会花费相当多的时间)。或者如何修改此代码以应用工作表索引,例如:sheets(3)
?
Private Function GetValue(path, file, sheet, ref)
Dim arg As String
'Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
'Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
'Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
End Function
Sub TestGetValue()
p = "c:\XLFiles\Budget"
f = "Budget.xls"
s = "Sheet1"
a = "A1"
MsgBox GetValue(p, f, s, a)
End Sub
最佳答案
VBA 可以很好地处理 unicode,但 VBA 编辑器不显示它。如果您不习惯的话,这可能会使 unicode 难以在 VBA 中使用。
当第一次需要使用 unicode 时(大多数人使用随机曲线来获得可爱的文本效果,但也有整个俄罗斯网站),我通过将 unicode 字符串放入工作表中来解决这个问题(工作表显示 unicode 很好) ,然后通过从工作表中提取变量值来设置变量。
因此,设置一个名为“UniSrc”的工作表(名称可以是任何名称),在 A 到 D 列中包含路径、文件、工作表和地址。将 unicode 工作表名称复制并粘贴到 C 列中。
这是您的测试程序,经过修改后可以这样工作:
Sub TestGetValue()
dim rowNow as long, wks as excel.worksheet
dim p as string, f as string, s as string, a as string
rowNow = 2 ' assuming row 1 is a header
set wks = thisworkbook.sheets("UniSrc")
with wks
p = .cells(rowNow, 1) ' path
f = .cells(rowNow, 2) ' file name
s = .cells(rowNow, 3) ' unicode name of sheet sought
a = .cells(rowNow, 4) ' cell address sought
end with
MsgBox GetValue(p, f, s, a)
End Sub
现在我们需要更新您的 GetValue 函数:
Function GetValue(sPath as string, sFile as string, sSheet as string, sAddress as string) as variant
Dim arg As String, vTmp as variant
If Right(sPath, 1) <> "\" Then sPath = sPath & "\"
If Dir(sPath & sFile) = "" Then ' Make sure the file exists
vTmp = "File Not Found"
else ' Create the argument
arg = "'" & sPath & "[" & sFile & "]" & sSheet & "'!" & _
Range(sAddress).Range("A1").Address(, , xlR1C1)
'Execute an XLM macro
vTmp = ExecuteExcel4Macro(arg)
End If
GetValue = vTmp
End Function
看你怎么走。我在平板电脑上,所以我随手写下了这个,无法测试它,但要点就在那里。
关于vba - 如何在 VBA 中处理工作表(unicode VBA 显示和处理)中西里尔字母引起的错误(#REF)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42741768/